-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2333 lines (1947 loc) · 88.7 KB
/
main.py
File metadata and controls
2333 lines (1947 loc) · 88.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
from __future__ import annotations
import uvicorn
from fastapi import FastAPI, HTTPException, Depends, Body, status, Response
from pydantic import BaseModel, Field, model_validator
from typing import List, Any, Dict, Optional, Tuple
import databases
import sqlite3
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi.responses import FileResponse
INDEX_HTML = Path(__file__).with_name("index.html")
# ====================================================================
# 1. НАСТРОЙКА БАЗЫ ДАННЫХ
# ====================================================================
DATABASE_URL = "sqlite:///./forms.db"
database = databases.Database(DATABASE_URL)
@asynccontextmanager
async def lifespan(app: FastAPI):
# При старте
await database.connect()
# Включаем поддержку FOREIGN KEY для SQLite на уровне подключения
await database.execute("PRAGMA foreign_keys = ON;")
yield
# При выключении
await database.disconnect()
app = FastAPI(
title="Полный Form Engine API (Админка + Рантайм + Справочники)",
lifespan=lifespan
)
# ====================================================================
# 2. HELPER-ФУНКЦИИ ДЛЯ АДМИНКИ (ПОИСК ID)
# ====================================================================
async def _get_id_by_code(table_name: str, code: str) -> int:
"""Универсальный помощник для получения ID из справочников."""
query = f"SELECT id FROM {table_name} WHERE code = :code"
row = await database.fetch_one(query, {"code": code})
if not row:
raise HTTPException(status_code=404, detail=f"Код '{code}' не найден в таблице '{table_name}'")
return row.id
async def _get_field_id_by_code(
form_id: int,
field_code: str,
allowed_step_ids: Optional[Tuple[int, ...]] = None,
) -> int:
"""Находит Field ID по его коду в рамках всей формы.
Если передан ``allowed_step_ids`` — дополнительно проверяем, что поле
принадлежит одному из разрешённых шагов (используется, например, в
конструкторе переходов, где условия должны ссылаться только на источник).
"""
query = """
SELECT f.id AS field_id, f.step_id
FROM step_fields f
JOIN form_steps s ON f.step_id = s.id
WHERE s.form_id = :form_id AND f.code = :field_code
"""
row = await database.fetch_one(query, {"form_id": form_id, "field_code": field_code})
if not row:
raise HTTPException(status_code=404, detail=f"Поле с кодом '{field_code}' не найдено в форме {form_id}")
if allowed_step_ids and row.step_id not in allowed_step_ids:
raise HTTPException(
status_code=400,
detail=(
f"Поле '{field_code}' не принадлежит разрешённым шагам: "
f"{', '.join(map(str, allowed_step_ids))}"
),
)
return row.field_id
async def _get_field_id_in_step(step_id: int, field_code: str) -> int:
"""Находит Field ID по коду в рамках конкретного шага."""
row = await database.fetch_one(
"SELECT id FROM step_fields WHERE step_id = :step_id AND code = :code",
{"step_id": step_id, "code": field_code}
)
if not row:
raise HTTPException(status_code=404, detail=f"Поле с кодом '{field_code}' не найдено на шаге {step_id}")
return row.id
async def _ensure_step_in_form(form_id: int, step_id: int) -> None:
row = await database.fetch_one(
"SELECT id FROM form_steps WHERE id = :step_id AND form_id = :form_id",
{"step_id": step_id, "form_id": form_id}
)
if not row:
raise HTTPException(status_code=404, detail=f"Шаг {step_id} не найден в форме {form_id}")
async def _fetch_step(step_id: int) -> StepRead:
query = """
SELECT s.*, st.code AS step_type_code
FROM form_steps s
JOIN step_types st ON s.step_type_id = st.id
WHERE s.id = :step_id
"""
row = await database.fetch_one(query, {"step_id": step_id})
if not row:
raise HTTPException(status_code=404, detail=f"Шаг {step_id} не найден")
return StepRead(**row)
async def _fetch_conditions(group_id: int) -> List[ConditionRead]:
query_conditions = """
SELECT c.id, c.field_id, c.op_id, c.value_text, c.value_num, c.value_bool,
c.value_date, c.option_code, c.position, c.rhs_field_id,
sf.code AS field_code, sf.title AS field_title,
rhs.code AS rhs_field_code,
co.code AS op_code, co.title AS op_title
FROM conditions c
JOIN step_fields sf ON c.field_id = sf.id
JOIN compare_ops co ON c.op_id = co.id
LEFT JOIN step_fields rhs ON c.rhs_field_id = rhs.id
WHERE c.group_id = :group_id
ORDER BY c.position
"""
condition_rows = await database.fetch_all(query_conditions, {"group_id": group_id})
return [
ConditionRead(
id=row.id,
field_id=row.field_id,
field_code=row.field_code,
field_title=row.field_title,
op_code=row.op_code,
op_title=row.op_title,
value_text=row.value_text,
value_num=row.value_num,
value_bool=row.value_bool,
value_date=row.value_date,
option_code=row.option_code,
rhs_field_code=row.rhs_field_code,
rhs_field_id=row.rhs_field_id,
position=row.position
)
for row in condition_rows
]
async def _fetch_route(route_id: int, form_id: int) -> StepRouteRead:
query_route = """
SELECT t.id, t.form_id, t.source_step_id, t.target_step_id, t.priority,
t.description, g.id AS condition_group_id, g.logic_op,
g.description AS scenario_description
FROM step_transitions t
JOIN condition_groups g ON t.condition_group_id = g.id
WHERE t.id = :route_id AND t.form_id = :form_id
"""
route_row = await database.fetch_one(query_route, {"route_id": route_id, "form_id": form_id})
if not route_row:
raise HTTPException(status_code=404, detail=f"Переход {route_id} не найден в форме {form_id}")
conditions = await _fetch_conditions(route_row.condition_group_id)
return StepRouteRead(
id=route_row.id,
form_id=route_row.form_id,
source_step_id=route_row.source_step_id,
target_step_id=route_row.target_step_id,
priority=route_row.priority,
description=route_row.description,
scenario_description=route_row.scenario_description,
logic_op=route_row.logic_op,
condition_group_id=route_row.condition_group_id,
conditions=conditions
)
async def _fetch_routes_for_step(form_id: int, step_id: int) -> List[StepRouteRead]:
query_ids = """
SELECT id
FROM step_transitions
WHERE form_id = :form_id AND source_step_id = :step_id
ORDER BY priority, id
"""
rows = await database.fetch_all(query_ids, {"form_id": form_id, "step_id": step_id})
result: List[StepRouteRead] = []
for row in rows:
result.append(await _fetch_route(row.id, form_id))
return result
async def _fetch_field(field_id: int) -> FieldRead:
query = """
SELECT
f.*, dt.code AS data_type_code, it.code AS input_type_code,
d.code AS dictionary_code
FROM step_fields f
JOIN field_data_types dt ON f.data_type_id = dt.id
JOIN field_input_types it ON f.input_type_id = it.id
LEFT JOIN dictionaries d ON f.dictionary_id = d.id
WHERE f.id = :field_id
"""
row = await database.fetch_one(query, {"field_id": field_id})
if not row:
raise HTTPException(status_code=404, detail=f"Поле {field_id} не найдено")
options: List[FieldOptionCreate] = []
if row.input_type_code in ('select', 'multiselect'):
if row.dictionary_id:
options_rows = await database.fetch_all(
"SELECT value_code, value_label, sort_order FROM dictionary_values WHERE dictionary_id = :id ORDER BY sort_order",
{"id": row.dictionary_id}
)
else:
options_rows = await database.fetch_all(
"SELECT value_code, value_label, sort_order FROM field_options WHERE field_id = :id ORDER BY sort_order",
{"id": row.id}
)
options = [FieldOptionCreate(**opt) for opt in options_rows]
return FieldRead(**row, options=options)
async def _fetch_visibility_rule(rule_id: int) -> VisibilityRuleRead:
query_rule = """
SELECT r.id, r.step_id, r.priority,
a.code AS action_code, a.title AS action_title,
g.id AS condition_group_id, g.logic_op,
g.description AS scenario_description
FROM field_visibility_rules r
JOIN visibility_actions a ON r.action_id = a.id
JOIN condition_groups g ON r.condition_group_id = g.id
WHERE r.id = :rule_id
"""
row = await database.fetch_one(query_rule, {"rule_id": rule_id})
if not row:
raise HTTPException(status_code=404, detail=f"Правило видимости {rule_id} не найдено")
conditions = await _fetch_conditions(row.condition_group_id)
targets_query = """
SELECT t.sort_order, f.id AS field_id, f.code, f.title
FROM visibility_targets t
JOIN step_fields f ON t.field_id = f.id
WHERE t.visibility_rule_id = :rule_id
ORDER BY t.sort_order, f.id
"""
targets_rows = await database.fetch_all(targets_query, {"rule_id": rule_id})
targets = [
VisibilityTargetRead(
field_id=target.field_id,
field_code=target.code,
field_title=target.title,
sort_order=target.sort_order
)
for target in targets_rows
]
return VisibilityRuleRead(
id=row.id,
step_id=row.step_id,
priority=row.priority,
action_code=row.action_code,
action_title=row.action_title,
condition_group_id=row.condition_group_id,
logic_op=row.logic_op,
scenario_description=row.scenario_description,
conditions=conditions,
targets=targets
)
async def _fetch_step_visibility_rules(step_id: int) -> List[VisibilityRuleRead]:
rows = await database.fetch_all(
"SELECT id FROM field_visibility_rules WHERE step_id = :step_id ORDER BY priority, id",
{"step_id": step_id}
)
return [await _fetch_visibility_rule(row.id) for row in rows]
# ====================================================================
# 3. PYDANTIC МОДЕЛИ ДЛЯ "АДМИНКИ" (CRUD)
# ====================================================================
# --- Формы (Forms) ---
class FormBase(BaseModel):
code: str
title: str
description: Optional[str] = None
class FormCreate(FormBase): pass
class FormRead(FormBase):
id: int
is_active: bool
start_step_id: Optional[int] = None
created_at: Any # datetime
# --- Шаги (Steps) ---
class StepBase(BaseModel):
code: str
title: str
step_type_code: str # 'questionnaire', 'upload', etc.
sort_order: int = 100
is_terminal: bool = False
class StepCreate(StepBase): pass
class StepRead(StepBase):
id: int
form_id: int
class StepUpdate(BaseModel):
title: Optional[str] = None
step_type_code: Optional[str] = None
sort_order: Optional[int] = None
is_terminal: Optional[bool] = None
is_start: Optional[bool] = None
# --- Справочники (Dictionaries) <--- НОВОЕ
class DictionaryValueCreate(BaseModel):
value_code: str
value_label: str
sort_order: int = 100
class DictionaryBase(BaseModel):
code: str
title: str
class DictionaryCreate(DictionaryBase):
values: List[DictionaryValueCreate] = []
class DictionaryRead(DictionaryBase):
id: int
values: List[DictionaryValueCreate] = []
# --- Поля (Fields) ---
class FieldOptionCreate(BaseModel):
value_code: str
value_label: str
sort_order: int = 100
class FieldBase(BaseModel):
code: str
title: str
data_type_code: str
input_type_code: str
is_required: bool = False
default_hidden: bool = False
sort_order: int = 100
class FieldCreate(FieldBase):
# Поле может иметь ЛИБО локальные опции, ЛИБО ссылку на справочник
options: Optional[List[FieldOptionCreate]] = None
dictionary_code: Optional[str] = None
@model_validator(mode='before')
def check_options_or_dictionary(cls, values):
options = values.get('options')
dictionary_code = values.get('dictionary_code')
input_type = values.get('input_type_code')
if input_type in ('select', 'multiselect'):
if options is not None and dictionary_code is not None:
raise ValueError("Поле не может иметь 'options' и 'dictionary_code' одновременно")
if options is None and dictionary_code is None:
raise ValueError("Поля 'select' и 'multiselect' должны иметь 'options' или 'dictionary_code'")
else:
if options is not None or dictionary_code is not None:
raise ValueError(f"Поле с типом '{input_type}' не может иметь 'options' или 'dictionary_code'")
return values
class FieldRead(FieldBase):
id: int
step_id: int
# UI всегда получает 'options', независимо от источника (локальный или глобальный)
options: List[FieldOptionCreate] = []
dictionary_code: Optional[str] = None # Для админки, чтобы знала что привязано
class FieldUpdate(BaseModel):
code: Optional[str] = None
title: Optional[str] = None
data_type_code: Optional[str] = None
input_type_code: Optional[str] = None
is_required: Optional[bool] = None
default_hidden: Optional[bool] = None
sort_order: Optional[int] = None
dictionary_code: Optional[str] = None
options: Optional[List[FieldOptionCreate]] = None
# --- Условия и Переходы (Conditions & Transitions) ---
class ConditionBase(BaseModel):
field_code: str
op_code: str
value_text: Optional[str] = None
value_num: Optional[float] = None
value_bool: Optional[bool] = None
value_date: Optional[str] = None
option_code: Optional[str] = None
rhs_field_code: Optional[str] = None
position: int = 100
class ConditionCreate(ConditionBase):
pass
class ConditionRead(ConditionBase):
id: int
field_id: int
field_title: str
op_title: str
rhs_field_id: Optional[int] = None
class VisibilityTargetCreate(BaseModel):
field_code: str
sort_order: int = 100
class VisibilityTargetRead(BaseModel):
field_id: int
field_code: str
field_title: str
sort_order: int
class VisibilityRuleBase(BaseModel):
priority: int = 100
action_code: str
scenario_description: Optional[str] = None
logic_op: str = "AND"
conditions: List[ConditionCreate] = Field(default_factory=list)
targets: List[VisibilityTargetCreate] = Field(default_factory=list)
class VisibilityRuleCreate(VisibilityRuleBase):
pass
class VisibilityRuleUpdate(VisibilityRuleBase):
pass
class VisibilityRuleRead(BaseModel):
id: int
step_id: int
priority: int
action_code: str
action_title: str
condition_group_id: int
logic_op: str
scenario_description: Optional[str] = None
conditions: List[ConditionRead] = []
targets: List[VisibilityTargetRead] = []
class StepRouteBase(BaseModel):
target_step_id: int
priority: int = 100
description: Optional[str] = None
scenario_description: Optional[str] = None
logic_op: str = "AND"
conditions: List[ConditionCreate] = Field(default_factory=list)
class StepRouteCreate(StepRouteBase):
pass
class StepRouteUpdate(StepRouteBase):
pass
class StepRouteRead(StepRouteBase):
id: int
form_id: int
source_step_id: int
conditions: List[ConditionRead] = Field(default_factory=list)
class InstanceSummary(BaseModel):
id: int
form_id: int
user_id: int
status_code: str
current_step_code: Optional[str] = None
started_at: Any
updated_at: Any
completed_steps: List[str] = Field(default_factory=list)
available_steps: List[str] = Field(default_factory=list)
class InstanceFieldAnswer(BaseModel):
field_code: str
field_title: str
value: Any
class InstanceStepAnswers(BaseModel):
step_id: int
step_code: str
step_title: str
status: Optional[str] = None
answers: List[InstanceFieldAnswer] = Field(default_factory=list)
class InstanceDetail(BaseModel):
id: int
form_id: int
form_code: str
user_id: int
status_code: str
started_at: Any
updated_at: Any
steps: List[InstanceStepAnswers] = Field(default_factory=list)
condition_group_id: Optional[int] = None
conditions: List[ConditionRead] = Field(default_factory=list)
# --- Универсальные справочные строки ---
class ReferenceRow(BaseModel):
id: int
code: str
title: str
# ====================================================================
# 4. API ЭНДПОИНТЫ "АДМИНКИ" (CRUD)
# ====================================================================
# --- CRUD для Форм (Forms) ---
@app.post("/admin/forms", response_model=FormRead, tags=["Admin - Forms"])
async def create_form(form: FormCreate):
"""Создает новую пустую форму (анкету)."""
query = "INSERT INTO forms (code, title, description) VALUES (:code, :title, :description) RETURNING *"
try:
new_form = await database.fetch_one(query, form.dict())
return new_form
except sqlite3.IntegrityError as e:
raise HTTPException(status_code=400, detail=f"Форма с кодом '{form.code}' уже существует. {e}")
@app.get("/admin/forms", response_model=List[FormRead], tags=["Admin - Forms"])
async def get_forms_list():
query = "SELECT * FROM forms WHERE is_active = TRUE"
return await database.fetch_all(query)
@app.get("/admin/forms/{form_id}", response_model=FormRead, tags=["Admin - Forms"])
async def get_form_details(form_id: int):
query = "SELECT * FROM forms WHERE id = :form_id"
form = await database.fetch_one(query, {"form_id": form_id})
if not form: raise HTTPException(status_code=404, detail="Форма не найдена")
return form
# --- CRUD для Шагов (Steps) ---
@app.post("/admin/forms/{form_id}/steps", response_model=StepRead, tags=["Admin - Steps"])
async def create_step(form_id: int, step: StepCreate):
step_type_id = await _get_id_by_code("step_types", step.step_type_code)
query = """
INSERT INTO form_steps (form_id, step_type_id, code, title, sort_order, is_terminal)
VALUES (:form_id, :step_type_id, :code, :title, :sort_order, :is_terminal)
RETURNING *
"""
values = step.dict()
values["form_id"] = form_id
values["step_type_id"] = step_type_id
del values["step_type_code"]
try:
new_step = await database.fetch_one(query, values)
await database.execute(
"UPDATE forms SET start_step_id = :step_id WHERE id = :form_id AND start_step_id IS NULL",
{"step_id": new_step.id, "form_id": form_id}
)
return await _fetch_step(new_step.id)
except sqlite3.IntegrityError as e:
raise HTTPException(status_code=400, detail=f"Шаг с кодом '{step.code}' уже существует в этой форме. {e}")
@app.get("/admin/forms/{form_id}/steps", response_model=List[StepRead], tags=["Admin - Steps"])
async def get_form_steps(form_id: int):
query = """
SELECT s.id
FROM form_steps s
WHERE s.form_id = :form_id
ORDER BY s.sort_order, s.id
"""
rows = await database.fetch_all(query, {"form_id": form_id})
result: List[StepRead] = []
for row in rows:
result.append(await _fetch_step(row.id))
return result
@app.put("/admin/forms/{form_id}/steps/{step_id}", response_model=StepRead, tags=["Admin - Steps"])
async def update_step(form_id: int, step_id: int, data: StepUpdate):
await _ensure_step_in_form(form_id, step_id)
update_parts = []
values: Dict[str, Any] = {"form_id": form_id, "step_id": step_id}
if data.title is not None:
update_parts.append("title = :title")
values["title"] = data.title
if data.sort_order is not None:
update_parts.append("sort_order = :sort_order")
values["sort_order"] = data.sort_order
if data.is_terminal is not None:
update_parts.append("is_terminal = :is_terminal")
values["is_terminal"] = data.is_terminal
if data.step_type_code is not None:
step_type_id = await _get_id_by_code("step_types", data.step_type_code)
update_parts.append("step_type_id = :step_type_id")
values["step_type_id"] = step_type_id
if update_parts:
query = "UPDATE form_steps SET " + ", ".join(update_parts) + " WHERE id = :step_id AND form_id = :form_id"
await database.execute(query, values)
if data.is_start is not None:
if data.is_start:
await database.execute(
"UPDATE forms SET start_step_id = :step_id WHERE id = :form_id",
{"step_id": step_id, "form_id": form_id}
)
else:
await database.execute(
"UPDATE forms SET start_step_id = NULL WHERE id = :form_id AND start_step_id = :step_id",
{"form_id": form_id, "step_id": step_id}
)
return await _fetch_step(step_id)
# --- CRUD для Справочников (Dictionaries) <--- НОВОЕ ---
@app.post("/admin/dictionaries", response_model=DictionaryRead, status_code=status.HTTP_201_CREATED,
tags=["Admin - Dictionaries"])
async def create_dictionary(dictionary: DictionaryCreate):
"""Создает новый глобальный справочник и все его значения."""
async with database.transaction():
query_dict = "INSERT INTO dictionaries (code, title) VALUES (:code, :title) RETURNING id"
try:
dict_id = await database.fetch_val(query=query_dict,
values={"code": dictionary.code, "title": dictionary.title})
except sqlite3.IntegrityError:
raise HTTPException(status_code=400, detail=f"Справочник с кодом '{dictionary.code}' уже существует")
query_value = """
INSERT INTO dictionary_values (dictionary_id, value_code, value_label, sort_order)
VALUES (:dict_id, :value_code, :value_label, :sort_order)
"""
for value in dictionary.values:
await database.execute(query_value, {**value.dict(), "dict_id": dict_id})
return DictionaryRead(id=dict_id, **dictionary.dict())
@app.get("/admin/dictionaries", response_model=List[DictionaryRead], tags=["Admin - Dictionaries"])
async def get_dictionaries_list():
"""Получает список всех справочников с их значениями."""
query_dicts = "SELECT * FROM dictionaries"
dictionaries = await database.fetch_all(query_dicts)
result = []
for d in dictionaries:
query_values = "SELECT value_code, value_label, sort_order FROM dictionary_values WHERE dictionary_id = :id ORDER BY sort_order"
values = await database.fetch_all(query_values, {"id": d.id})
result.append(
DictionaryRead(id=d.id, code=d.code, title=d.title, values=[DictionaryValueCreate(**v) for v in values]))
return result
# ====================================================================
# 5. API ДЛЯ СИСТЕМНЫХ СПРАВОЧНИКОВ (STEP TYPES, DATA TYPES ...)
# ====================================================================
REFERENCE_TABLES: Dict[str, str] = {
"step_types": "step_types",
"field_data_types": "field_data_types",
"field_input_types": "field_input_types",
"compare_ops": "compare_ops",
"visibility_actions": "visibility_actions",
"instance_statuses": "instance_statuses",
}
async def _fetch_reference_rows(dict_code: str) -> List[ReferenceRow]:
table_name = REFERENCE_TABLES.get(dict_code)
if not table_name:
raise HTTPException(status_code=404, detail=f"Неизвестный справочник '{dict_code}'")
query = f"SELECT id, code, title FROM {table_name} ORDER BY id"
rows = await database.fetch_all(query)
return [ReferenceRow(**row) for row in rows]
@app.get("/dict/{dict_code}", response_model=List[ReferenceRow], tags=["Reference"])
async def get_reference_dict(dict_code: str):
return await _fetch_reference_rows(dict_code)
@app.get("/raw/{dict_code}", response_model=List[ReferenceRow], tags=["Reference"])
async def get_reference_raw(dict_code: str):
return await _fetch_reference_rows(dict_code)
# --- CRUD для Полей (Fields) ---
@app.post("/admin/steps/{step_id}/fields", response_model=FieldRead, tags=["Admin - Fields"])
async def create_field(step_id: int, field: FieldCreate):
"""
Создает новое поле.
Принимает ЛИБО 'options' (локальные), ЛИБО 'dictionary_code' (глобальные).
"""
data_type_id = await _get_id_by_code("field_data_types", field.data_type_code)
input_type_id = await _get_id_by_code("field_input_types", field.input_type_code)
dictionary_id = None
created_options = []
# <--- ОБНОВЛЕННАЯ ЛОГИКА
if field.dictionary_code:
dictionary_id = await _get_id_by_code("dictionaries", field.dictionary_code)
elif field.options:
created_options = field.options
# --->
async with database.transaction():
query_field = """
INSERT INTO step_fields (
step_id, code, title, data_type_id, input_type_id, dictionary_id,
is_required, default_hidden, sort_order
)
VALUES (
:step_id, :code, :title, :data_type_id, :input_type_id, :dictionary_id,
:is_required, :default_hidden, :sort_order
)
RETURNING id
"""
values = field.dict()
values["step_id"] = step_id
values["data_type_id"] = data_type_id
values["input_type_id"] = input_type_id
values["dictionary_id"] = dictionary_id # <--- НОВОЕ
del values["options"]
del values["dictionary_code"]
del values["data_type_code"]
del values["input_type_code"]
try:
field_id = await database.fetch_val(query=query_field, values=values)
except sqlite3.IntegrityError as e:
raise HTTPException(status_code=400, detail=f"Поле с кодом '{field.code}' уже существует на этом шаге. {e}")
# Если были переданы ЛОКАЛЬНЫЕ опции, создаем их
if created_options:
query_option = """
INSERT INTO field_options (field_id, value_code, value_label, sort_order)
VALUES (:field_id, :value_code, :value_label, :sort_order)
"""
for opt in created_options:
await database.execute(query_option, {**opt.dict(), "field_id": field_id})
# <--- ОБНОВЛЕННАЯ ЛОГИКА
# Теперь нужно прочитать опции, чтобы вернуть их в FieldRead
if dictionary_id:
query_read_opts = "SELECT value_code, value_label, sort_order FROM dictionary_values WHERE dictionary_id = :id"
options_rows = await database.fetch_all(query_read_opts, {"id": dictionary_id})
created_options = [FieldOptionCreate(**row) for row in options_rows]
# --->
return await _fetch_field(field_id)
@app.get("/admin/steps/{step_id}/fields", response_model=List[FieldRead], tags=["Admin - Fields"])
async def get_step_fields(step_id: int):
"""
Получает все поля для шага.
Корректно отдает 'options' из 'dictionaries' ИЛИ 'field_options'.
"""
# <--- ОБНОВЛЕННЫЙ ЗАПРОС
query = """
SELECT
f.*,
dt.code AS data_type_code,
it.code AS input_type_code,
d.code AS dictionary_code
FROM step_fields f
JOIN field_data_types dt ON f.data_type_id = dt.id
JOIN field_input_types it ON f.input_type_id = it.id
LEFT JOIN dictionaries d ON f.dictionary_id = d.id
WHERE f.step_id = :step_id
ORDER BY f.sort_order
"""
fields_rows = await database.fetch_all(query, {"step_id": step_id})
result = []
for field in fields_rows:
options = []
# <--- ОБНОВЛЕННАЯ ЛОГИКА
if field.input_type_code in ('select', 'multiselect'):
if field.dictionary_id:
# Берем опции из ГЛОБАЛЬНОГО справочника
query_options = "SELECT value_code, value_label, sort_order FROM dictionary_values WHERE dictionary_id = :id ORDER BY sort_order"
options_rows = await database.fetch_all(query_options, {"id": field.dictionary_id})
options = [FieldOptionCreate(**row) for row in options_rows]
else:
# Берем опции из ЛОКАЛЬНЫХ
query_options = "SELECT value_code, value_label, sort_order FROM field_options WHERE field_id = :id ORDER BY sort_order"
options_rows = await database.fetch_all(query_options, {"id": field.id})
options = [FieldOptionCreate(**row) for row in options_rows]
result.append(FieldRead(**field, options=options))
return result
@app.get("/admin/fields/{field_id}", response_model=FieldRead, tags=["Admin - Fields"])
async def get_field(field_id: int):
return await _fetch_field(field_id)
@app.put("/admin/fields/{field_id}", response_model=FieldRead, tags=["Admin - Fields"])
async def update_field(field_id: int, field: FieldUpdate):
query_current = """
SELECT
f.id, f.step_id, f.code, f.title, f.data_type_id, f.input_type_id,
f.is_required, f.sort_order, f.dictionary_id, f.default_hidden,
dt.code AS data_type_code,
it.code AS input_type_code,
d.code AS dictionary_code
FROM step_fields f
JOIN field_data_types dt ON f.data_type_id = dt.id
JOIN field_input_types it ON f.input_type_id = it.id
LEFT JOIN dictionaries d ON f.dictionary_id = d.id
WHERE f.id = :field_id
"""
current = await database.fetch_one(query_current, {"field_id": field_id})
if not current:
raise HTTPException(status_code=404, detail=f"Поле {field_id} не найдено")
options_rows = await database.fetch_all(
"SELECT value_code, value_label, sort_order FROM field_options WHERE field_id = :field_id ORDER BY sort_order",
{"field_id": field_id}
)
incoming = field.dict(exclude_unset=True)
final_code = incoming.get('code', current.code)
final_title = incoming.get('title', current.title)
final_data_type_code = incoming.get('data_type_code', current.data_type_code)
final_input_type_code = incoming.get('input_type_code', current.input_type_code)
final_is_required = incoming.get('is_required', bool(current.is_required))
final_sort_order = incoming.get('sort_order', current.sort_order)
final_default_hidden = incoming.get('default_hidden', bool(current.default_hidden))
final_default_hidden = bool(final_default_hidden)
dictionary_code_provided = 'dictionary_code' in incoming
options_provided = 'options' in incoming
final_dictionary_code = incoming.get('dictionary_code', current.dictionary_code)
provided_options: Optional[List[FieldOptionCreate]] = incoming.get('options') if options_provided else None
# Приводим пустые значения к None
if isinstance(final_dictionary_code, str) and final_dictionary_code.strip() == "":
final_dictionary_code = None
if final_input_type_code not in ('select', 'multiselect'):
if dictionary_code_provided and final_dictionary_code is not None:
raise HTTPException(status_code=400, detail="Для данного input_type нельзя указать dictionary_code")
if options_provided and provided_options:
raise HTTPException(status_code=400, detail="Для данного input_type нельзя указывать options")
dictionary_id = None
options_to_write: Optional[List[FieldOptionCreate]] = []
else:
dictionary_id = current.dictionary_id
options_to_write: Optional[List[FieldOptionCreate]] = None
if final_dictionary_code and provided_options:
raise HTTPException(status_code=400, detail="Поле не может одновременно иметь dictionary_code и options")
if dictionary_code_provided:
if final_dictionary_code is None:
dictionary_id = None
else:
dictionary_id = await _get_id_by_code("dictionaries", final_dictionary_code)
options_to_write = []
if options_provided:
options_to_write = provided_options or []
dictionary_id = None
if options_to_write is None:
# Значит пользователь ничего не менял – используем текущее состояние
if dictionary_id:
options_to_write = []
else:
options_to_write = [FieldOptionCreate(**row) for row in options_rows]
if not dictionary_id and not options_to_write:
raise HTTPException(status_code=400, detail="Для select/multiselect необходимо указать dictionary_code или options")
data_type_id = await _get_id_by_code("field_data_types", final_data_type_code)
input_type_id = await _get_id_by_code("field_input_types", final_input_type_code)
update_parts = [
"code = :code",
"title = :title",
"data_type_id = :data_type_id",
"input_type_id = :input_type_id",
"is_required = :is_required",
"default_hidden = :default_hidden",
"sort_order = :sort_order",
"dictionary_id = :dictionary_id"
]
values = {
"field_id": field_id,
"code": final_code,
"title": final_title,
"data_type_id": data_type_id,
"input_type_id": input_type_id,
"is_required": final_is_required,
"default_hidden": final_default_hidden,
"sort_order": final_sort_order,
"dictionary_id": dictionary_id
}
try:
await database.execute(
"UPDATE step_fields SET " + ", ".join(update_parts) + " WHERE id = :field_id",
values
)
except sqlite3.IntegrityError as exc:
raise HTTPException(status_code=400, detail=f"Не удалось обновить поле: {exc}")
# Обновляем локальные опции
if final_input_type_code in ('select', 'multiselect'):
if options_to_write is not None:
await database.execute("DELETE FROM field_options WHERE field_id = :field_id", {"field_id": field_id})
for opt in options_to_write:
await database.execute(
"""
INSERT INTO field_options (field_id, value_code, value_label, sort_order)
VALUES (:field_id, :value_code, :value_label, :sort_order)
""",
{"field_id": field_id, **opt.dict()}
)
else:
await database.execute("DELETE FROM field_options WHERE field_id = :field_id", {"field_id": field_id})
return await _fetch_field(field_id)
@app.get(
"/admin/forms/{form_id}/steps/{step_id}/visibility",
response_model=List[VisibilityRuleRead],
tags=["Admin - Fields"]
)
async def list_visibility_rules(form_id: int, step_id: int):
await _ensure_step_in_form(form_id, step_id)
rows = await database.fetch_all(
"SELECT id FROM field_visibility_rules WHERE step_id = :step_id ORDER BY priority, id",
{"step_id": step_id}
)
result: List[VisibilityRuleRead] = []
for row in rows:
result.append(await _fetch_visibility_rule(row.id))
return result
@app.post(
"/admin/forms/{form_id}/steps/{step_id}/visibility",
response_model=VisibilityRuleRead,
status_code=status.HTTP_201_CREATED,
tags=["Admin - Fields"]
)
async def create_visibility_rule(form_id: int, step_id: int, rule: VisibilityRuleCreate):