Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
2505 lines (2207 loc) · 97.9 KB
/
Copy pathapp.py
File metadata and controls
2505 lines (2207 loc) · 97.9 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
"""공과금 정산 시스템 — Flask 애플리케이션.
DB 계층은 SQLite 기반이며 스키마는 ``models.py`` + ``migrations/`` 가 정의한다.
MySQL 의존성과 하드코딩된 자격증명은 제거되었다.
실행::
flask db upgrade # 스키마 생성/갱신
flask seed-settings # 설정 기본값 시딩 (멱등)
python app.py
배분 계산은 Decimal 기반으로 처리하며, 사용자 입력은 저장 전에 검증한다.
"""
import json
import hashlib
import secrets
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from functools import wraps
from pathlib import Path
import click
from flask import (
Flask,
abort,
current_app,
flash,
jsonify,
redirect,
render_template,
request,
session,
url_for,
)
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.orm import joinedload, selectinload
from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer
from markupsafe import Markup
import balance as balance_service
from backup_format import (
BackupFormatError,
export_payload,
prepare_restore,
replace_all,
validate_sqlite_backup,
)
from calculation_service import (
AllocationError,
allocate_common,
allocate_electric,
allocate_water,
round_up_to_10 as allocation_round_up_to_10,
)
from config import Config, ensure_data_dir
from extensions import db, migrate, register_sqlite_pragmas
from models import (
CommonBill,
CommonBillDetail,
ElectricBill,
ElectricBillDetail,
ElectricBillMonth,
ElectricReading,
FinalInvoice,
FinalInvoiceCharge,
Floor,
InvoiceCombination,
InvoiceCombinationItem,
Payment,
Setting,
Unit,
WaterBill,
WaterBillDetail,
)
from settings_registry import SETTING_DEFS, SETTING_KEYS, get_def
from onboarding_state import mark_onboarding_completed, onboarding_completed
from tutorial_service import (
cleanup_stale_tutorial_databases,
create_tutorial_database,
delete_tutorial_database,
inspect_tutorial_database,
)
from tutorial_runtime import launch_tutorial_process, stop_tutorial_process
# =========================
# Safe numeric helpers & JSON provider (Decimal-safe)
# =========================
try:
from flask.json.provider import DefaultJSONProvider
except ImportError: # pragma: no cover - Flask 2 이하
DefaultJSONProvider = None
def dec(val, q=None):
"""임의 입력을 Decimal 로 변환한다. 실패 시 0.
계산 로직이 의존하는 함수이므로 동작을 변경하지 않았다.
"""
if isinstance(val, Decimal):
x = val
elif isinstance(val, (int, float)):
x = Decimal(str(val))
else:
try:
s = (val if val is not None else "").strip()
except (AttributeError, TypeError):
s = str(val or "")
if s == "":
x = Decimal("0")
else:
try:
x = Decimal(s.replace(",", ""))
except InvalidOperation:
x = Decimal("0")
if q:
try:
x = x.quantize(q)
except InvalidOperation:
pass
return x
def parse_amount(value, label, *, allow_negative=False, default=None):
"""사용자 금액 입력을 검증한다. 생략 가능한 필드는 default 를 지정한다."""
if value is None or (isinstance(value, str) and not value.strip()):
if default is None:
raise ValueError("{}을(를) 입력해주세요.".format(label))
return Decimal(str(default))
try:
amount = Decimal(str(value).strip().replace(",", ""))
except (InvalidOperation, ValueError):
raise ValueError("{}이(가) 올바른 숫자가 아닙니다.".format(label))
if not amount.is_finite():
raise ValueError("{}이(가) 올바른 숫자가 아닙니다.".format(label))
if amount < 0 and not allow_negative:
raise ValueError("{}은(는) 음수일 수 없습니다.".format(label))
return amount
def parse_json_bool(value, label):
if not isinstance(value, bool):
raise ValueError("{}은(는) true 또는 false여야 합니다.".format(label))
return value
def to_int(val, default=0):
try:
s = (val if val is not None else "").strip()
except (AttributeError, TypeError):
s = str(val or "")
if s == "":
return default
try:
number = Decimal(s.replace(",", ""))
if not number.is_finite() or number != number.to_integral_value():
return default
return int(number)
except (InvalidOperation, TypeError, ValueError):
return default
def parse_nonnegative_int(value, label):
number = to_int(value, None)
if number is None or number < 0:
raise ValueError("{}은(는) 0 이상의 정수여야 합니다.".format(label))
return number
# ======================================================
# Flask / DB bootstrap
# ======================================================
def create_app(config_object=Config):
application = Flask(__name__)
application.config.from_object(config_object)
if DefaultJSONProvider is not None:
class DecimalJSONProvider(DefaultJSONProvider):
def default(self, o):
if isinstance(o, Decimal):
return float(o)
return super().default(o)
application.json = DecimalJSONProvider(application)
register_sqlite_pragmas(application.config["SQLITE_PRAGMAS"])
ensure_data_dir()
db.init_app(application)
# render_as_batch: SQLite 는 ALTER TABLE 로 제약을 바꿀 수 없으므로
# Alembic 이 "새 테이블 생성 → 복사 → 교체" 방식을 쓰게 한다.
migrate.init_app(application, db, render_as_batch=True, compare_type=True)
application.jinja_env.globals["csrf_token"] = generate_csrf_token
application.jinja_env.globals["asset_url"] = asset_url
application.jinja_env.globals["stylesheet_asset"] = stylesheet_asset
application.jinja_env.globals["script_asset"] = script_asset
register_cli(application)
return application
# ======================================================
# CSRF
# ======================================================
def generate_csrf_token():
if "_csrf_token" not in session:
session["_csrf_token"] = secrets.token_hex(16)
return session["_csrf_token"]
def asset_url(filename):
"""정적 자원의 안정적인 주소를 반환한다.
튜토리얼 서버는 일회성 포트에서 실행되므로 CSS·JavaScript는 수명이 긴
메인 앱 서버에서 받는다. 패키징 버전은 쿼리에 붙여 업데이트 뒤에도
Electron 캐시에 남은 이전 자원이 재사용되지 않게 한다.
"""
values = {"filename": filename}
version = str(current_app.config.get("APP_VERSION") or "").strip()
if version:
values["v"] = version
path = url_for("static", **values)
if current_app.config.get("TUTORIAL_MODE"):
main_url = str(current_app.config.get("TUTORIAL_MAIN_URL") or "").rstrip("/")
if main_url:
return main_url + path
return path
def _static_asset_text(filename):
static_root = Path(current_app.static_folder).resolve()
target = (static_root / str(filename)).resolve()
if static_root != target.parent and static_root not in target.parents:
raise ValueError("정적 자원 경로가 올바르지 않습니다.")
try:
return target.read_text(encoding="utf-8")
except OSError as error:
raise RuntimeError("튜토리얼 자원을 읽을 수 없습니다: {}".format(filename)) from error
def stylesheet_asset(filename):
"""튜토리얼 CSS는 HTML에 포함하고 일반 화면은 정적 파일로 제공한다."""
if not current_app.config.get("TUTORIAL_MODE"):
return Markup('<link rel="stylesheet" href="{}">').format(asset_url(filename))
return Markup('<style data-inline-stylesheet="{}">\n{}\n</style>').format(
filename, Markup(_static_asset_text(filename))
)
def script_asset(filename):
"""화면 이동 뒤에도 튜토리얼 동작 파일을 HTML과 함께 확실히 전달한다."""
if not current_app.config.get("TUTORIAL_MODE"):
return Markup('<script src="{}"></script>').format(asset_url(filename))
return Markup('<script data-inline-script="{}">\n{}\n</script>').format(
filename, Markup(_static_asset_text(filename))
)
def csrf_protect(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if request.method == "POST":
token = session.get("_csrf_token", None)
req_token = request.form.get("_csrf_token") or (
request.get_json(silent=True) or {}
).get("_csrf_token")
if not token or token != req_token:
return jsonify({"success": False, "message": "CSRF 토큰이 유효하지 않습니다."}), 403
return f(*args, **kwargs)
return decorated_function
# ======================================================
# Utils
# ======================================================
def round_up_to_10(amount):
"""10원 단위 올림. 도메인 정책이므로 구현을 변경하지 않는다."""
return allocation_round_up_to_10(amount)
def get_setting(key, default=None):
"""설정 값을 문자열로 조회한다.
등록되지 않은 키는 즉시 실패시킨다 (오타로 인한 조용한 기본값 사용 방지).
"""
definition = get_def(key)
row = Setting.query.filter_by(setting_key=key).first()
if row is None or row.setting_value is None:
return definition.default if default is None else default
return row.setting_value
def set_setting(key, value):
definition = get_def(key)
normalized = definition.normalize(value)
row = Setting.query.filter_by(setting_key=key).first()
if row:
row.setting_value = normalized
else:
db.session.add(Setting(setting_key=key, setting_value=normalized))
def all_settings():
"""등록된 전체 설정을 {key: 문자열} 로 반환한다."""
stored = {s.setting_key: s.setting_value for s in Setting.query.all()}
return {
d.key: stored.get(d.key) if stored.get(d.key) is not None else d.default
for d in SETTING_DEFS
}
def seed_settings():
"""등록된 설정 키의 기본값을 시딩한다. 기존 값은 덮어쓰지 않는다 (멱등)."""
existing = {s.setting_key for s in Setting.query.all()}
created = []
for definition in SETTING_DEFS:
if definition.key not in existing:
db.session.add(
Setting(setting_key=definition.key, setting_value=definition.default)
)
created.append(definition.key)
db.session.commit()
return created
def create_unit_snapshot(unit):
"""계산 시점의 세대 속성을 박제한다.
이 스냅샷 덕분에 세대 마스터가 나중에 바뀌어도 과거 정산 내역이 왜곡되지 않는다.
구조를 변경하지 않는다.
"""
return {
"unit_id": unit.id,
"floor_id": unit.floor_id,
"floor_number": unit.floor.floor_number,
"floor_name": unit.floor.name or "",
"unit_name": unit.unit_name,
"electric_welfare": unit.electric_welfare,
"electric_voucher": unit.electric_voucher,
"has_tv": unit.has_tv,
"water_welfare": unit.water_welfare,
"residents_count": unit.residents_count,
"is_vacant": unit.is_vacant,
}
def first_of_month(d):
return date(d.year, d.month, 1)
def parse_month_input(raw):
"""``<input type="month">`` 값('YYYY-MM') 또는 'YYYY-MM-DD' 를 그 달 1일로 변환한다.
실패 시 None. 기존에는 세 라우트에 흩어져 있던 정규화를 한 곳으로 모았다.
"""
if raw is None:
return None
text = str(raw).strip()
if not text:
return None
for fmt in ("%Y-%m", "%Y-%m-%d"):
try:
return datetime.strptime(text, fmt).date().replace(day=1)
except ValueError:
continue
return None
def json_error(message, status=200, **extra):
payload = {"success": False, "message": message}
payload.update(extra)
return jsonify(payload), status
def _serialize_allocation_preview(allocation):
"""순수 배분 결과를 화면에서 공통으로 표시할 수 있는 형태로 바꾼다."""
details = []
for row in allocation["details"]:
unit = row["unit"]
details.append({
"unit_id": unit.id,
"unit_name": unit.unit_name,
"floor_name": unit.floor.name if unit.floor else "",
"usage_amount": row.get("usage_amount"),
"base_amount": row.get("base_amount", row.get("amount", 0)),
"welfare_discount": row.get("welfare_discount", 0),
"voucher_discount": row.get("voucher_discount", 0),
"tv_fee": row.get("tv_fee", 0),
"unused_discount": row.get("unused_discount", 0),
"is_excluded": row.get("is_excluded", False),
"final_amount": row["final_amount"],
"charged_amount": row["charged_amount"],
})
return {
"details": details,
"warnings": allocation["warnings"],
"final_total": allocation["final_total"],
"charged_total": allocation["charged_total"],
"rounding_difference": allocation["rounding_difference"],
}
# ======================================================
# CLI
# ======================================================
def register_cli(application):
@application.cli.command("seed-settings")
def seed_settings_command():
"""설정 기본값을 시딩한다 (멱등)."""
created = seed_settings()
if created:
click.echo("시딩된 설정: {}".format(", ".join(created)))
else:
click.echo("모든 설정이 이미 존재합니다.")
@application.cli.command("check-db")
def check_db_command():
"""DB 정합성을 검증한다."""
from db_validate import run_all_checks, format_report
click.echo(format_report(run_all_checks()))
@application.cli.command("backup-db")
@click.option("--output", default=None, help="백업 파일 경로")
def backup_db_command(output):
"""SQLite 네이티브 backup API 로 안전하게 백업한다."""
from db_backup import backup_database
path = backup_database(output)
click.echo("백업 완료: {}".format(path))
app = create_app()
@app.context_processor
def tutorial_screen_context():
"""격리된 연습 서버의 모든 실제 화면에 안내 레이어 설정을 제공한다."""
if not app.config.get("TUTORIAL_MODE"):
return {"live_tutorial": None}
main_url = app.config.get("TUTORIAL_MAIN_URL", "").rstrip("/")
token = app.config.get("TUTORIAL_CONTROL_TOKEN", "")
latest_invoice = InvoiceCombination.query.order_by(
InvoiceCombination.created_at.desc(), InvoiceCombination.id.desc()
).first()
return {
"live_tutorial": {
"endpoint": request.endpoint,
"path": request.path,
"mainUrl": main_url,
"controlToken": token,
"controlBase": main_url + "/tutorial/control",
"hadUserData": bool(app.config.get("TUTORIAL_HAD_USER_DATA")),
"runId": app.config.get("TUTORIAL_RUN_ID", ""),
"latestInvoiceUrl": (
url_for("view_invoice", combination_id=latest_invoice.id)
if latest_invoice else None
),
"latestInvoicePrintUrl": (
url_for("print_invoice", combination_id=latest_invoice.id)
if latest_invoice else None
),
}
}
# ======================================================
# Routes - Core pages
# ======================================================
def _has_operational_data():
"""기본 설정 행만 있는 초기 DB와 사용 중인 DB를 구분한다."""
return any((
Floor.query.limit(1).first(),
Unit.query.limit(1).first(),
ElectricBill.query.limit(1).first(),
WaterBill.query.limit(1).first(),
CommonBill.query.limit(1).first(),
InvoiceCombination.query.limit(1).first(),
Payment.query.limit(1).first(),
))
@app.before_request
def offer_first_run_tutorial():
"""완료 전의 빈 DB에서만 주요 HTML 화면을 튜토리얼로 연결한다."""
if app.config.get("TUTORIAL_MODE"):
return None
if not app.config.get("ONBOARDING_ENABLED", True) or request.method != "GET":
return None
if request.endpoint not in {
"index", "settings", "calculator", "view_bills", "invoice_combination", "payments",
}:
return None
if session.get("onboarding_deferred"):
return None
if onboarding_completed(app.config["ONBOARDING_STATE_PATH"]):
return None
try:
if _has_operational_data():
return None
except SQLAlchemyError: # 스키마 준비 전에는 기존 오류 화면을 가로채지 않는다.
return None
return redirect(url_for("tutorial"))
@app.route("/tutorial")
def tutorial():
if app.config.get("TUTORIAL_MODE"):
return redirect(url_for("index"))
# 사용 안내를 여는 행위 자체가 새 연습의 시작이다. 이전 연습의 변경 내용과
# 진행 위치는 재사용하지 않고, 소유권이 확인된 전용 DB만 폐기한다.
previous_tutorial_id = session.get("tutorial_id")
if previous_tutorial_id:
try:
_stop_and_delete_tutorial(previous_tutorial_id)
except (OSError, RuntimeError, ValueError) as error:
session["onboarding_deferred"] = True
flash("이전 연습 데이터를 안전하게 정리하지 못해 새 연습을 시작하지 않았습니다: {}".format(error), "error")
return redirect(url_for("index")), 303
_clear_tutorial_session()
tutorial_id = secrets.token_hex(16)
session["tutorial_id"] = tutorial_id
session["tutorial_had_user_data"] = _has_operational_data()
session.pop("onboarding_deferred", None)
try:
cleanup_stale_tutorial_databases(app.config["TUTORIAL_DATA_DIR"])
path = create_tutorial_database(app.config["TUTORIAL_DATA_DIR"], tutorial_id)
control_token = URLSafeTimedSerializer(
app.secret_key, salt="live-tutorial-control-v1"
).dumps({"tutorial_id": tutorial_id})
running = launch_tutorial_process(
tutorial_id,
path,
request.host_url.rstrip("/"),
control_token,
preferred_port=session.get("tutorial_port"),
had_user_data=bool(session.get("tutorial_had_user_data")),
)
session["tutorial_port"] = running.port
return redirect("http://127.0.0.1:{}/".format(running.port))
except (OSError, RuntimeError, ValueError) as error:
# 빈 DB의 자동 안내가 시작 실패 → 자동 안내 재진입을 반복하지 않게 한다.
# 사용자는 본 화면에서 오류를 확인한 뒤 메뉴로 다시 시도할 수 있다.
try:
_stop_and_delete_tutorial(tutorial_id)
except (OSError, RuntimeError, ValueError):
pass
_clear_tutorial_session()
session["onboarding_deferred"] = True
flash("사용 안내를 시작하지 못했습니다: {}".format(error), "error")
return redirect(url_for("index")), 303
@app.route("/tutorial/health")
def tutorial_health():
if not app.config.get("TUTORIAL_MODE"):
abort(404)
from config import resolve_db_path
path = resolve_db_path()
try:
status = inspect_tutorial_database(path) if path else {
"ready": False,
"errors": ["튜토리얼 DB 경로를 확인할 수 없습니다."],
}
except (OSError, RuntimeError, ValueError) as error:
status = {"ready": False, "errors": [str(error)]}
payload = dict(status, success=bool(status.get("ready")), mode="tutorial",
dataset_ready=bool(status.get("ready")))
return jsonify(payload), 200 if status.get("ready") else 503
def _stop_and_delete_tutorial(tutorial_id):
stop_tutorial_process(tutorial_id)
delete_tutorial_database(app.config["TUTORIAL_DATA_DIR"], tutorial_id)
def _clear_tutorial_session():
session.pop("tutorial_id", None)
session.pop("tutorial_had_user_data", None)
session.pop("tutorial_port", None)
session.pop("onboarding_deferred", None)
def _finish_tutorial(next_action=None):
tutorial_id = session.get("tutorial_id")
try:
if tutorial_id:
_stop_and_delete_tutorial(tutorial_id)
mark_onboarding_completed(app.config["ONBOARDING_STATE_PATH"])
except (OSError, RuntimeError, ValueError) as error:
flash("사용 안내를 안전하게 종료하지 못했습니다: {}".format(error), "error")
return redirect(url_for("tutorial"))
had_user_data = bool(session.get("tutorial_had_user_data")) or _has_operational_data()
_clear_tutorial_session()
flash("사용 안내를 완료했습니다. 연습 데이터는 삭제되었습니다.", "success")
if had_user_data:
return redirect(url_for("index"))
if next_action == "import":
return redirect(url_for("settings", tab="import-export-tab"))
return redirect(url_for("settings", tab="floors-tab"))
def _exit_tutorial(handoff=False):
"""현재 일회성 연습을 완료 처리 없이 폐기하고 본 앱으로 돌아간다."""
tutorial_id = session.get("tutorial_id")
try:
if tutorial_id:
_stop_and_delete_tutorial(tutorial_id)
except (OSError, RuntimeError, ValueError) as error:
session["onboarding_deferred"] = True
flash("연습 데이터를 안전하게 삭제하지 못했습니다: {}".format(error), "error")
return redirect(url_for("index"))
_clear_tutorial_session()
session["onboarding_deferred"] = True
flash("연습을 종료했습니다. 연습 데이터와 진행 상태는 삭제되었습니다.", "info")
if handoff:
response = render_template(
"tutorial_exit_handoff.html", destination=url_for("index")
)
return response, 200, {"Cache-Control": "no-store"}
return redirect(url_for("index"))
@app.route("/tutorial/control/<action>")
def tutorial_control(action):
if action not in {"complete", "exit", "defer", "restart"}:
abort(404)
try:
signed = URLSafeTimedSerializer(
app.secret_key, salt="live-tutorial-control-v1"
).loads(request.args.get("token", ""), max_age=24 * 60 * 60)
except SignatureExpired:
abort(403, "사용 안내 연결 시간이 만료되었습니다.")
except BadSignature:
abort(403, "사용 안내 연결 정보가 올바르지 않습니다.")
tutorial_id = session.get("tutorial_id")
if not tutorial_id or signed.get("tutorial_id") != tutorial_id:
abort(403, "현재 사용 안내 세션과 일치하지 않습니다.")
if action == "complete":
return _finish_tutorial(request.args.get("next_action"))
if action in {"exit", "defer"}: # defer는 이전 화면에서 열린 요청과의 호환용이다.
# 연습 서버를 종료한 직후 포트가 바뀌는 흐름에서는 302 후속 이동이
# 일부 브라우저에서 멈출 수 있다. 본 앱이 직접 전환 화면을 내려준다.
return _exit_tutorial(handoff=True)
try:
_stop_and_delete_tutorial(tutorial_id)
except (OSError, RuntimeError, ValueError) as error:
flash("연습 데이터를 안전하게 초기화하지 못했습니다: {}".format(error), "error")
return redirect(url_for("tutorial"))
_clear_tutorial_session()
return redirect(url_for("tutorial"))
@app.route("/tutorial/restart", methods=["POST"])
@csrf_protect
def restart_tutorial():
tutorial_id = session.pop("tutorial_id", None)
if tutorial_id:
try:
_stop_and_delete_tutorial(tutorial_id)
except (OSError, RuntimeError, ValueError):
flash("기존 연습 데이터를 안전하게 확인하지 못해 새로 시작하지 않았습니다.", "error")
session["tutorial_id"] = tutorial_id
return redirect(url_for("tutorial"))
session.pop("tutorial_had_user_data", None)
session.pop("tutorial_port", None)
session.pop("onboarding_deferred", None)
return redirect(url_for("tutorial"))
@app.route("/tutorial/exit", methods=["POST"])
@app.route("/tutorial/defer", methods=["POST"])
@csrf_protect
def exit_tutorial():
return _exit_tutorial()
@app.route("/tutorial/complete", methods=["POST"])
@csrf_protect
def complete_tutorial():
return _finish_tutorial(request.form.get("next_action"))
@app.route("/")
def index():
floors_count = Floor.query.count()
units_count = Unit.query.count()
vacant_count = Unit.query.filter_by(is_vacant=True).count()
occupied_count = units_count - vacant_count
return render_template(
"index.html",
floors_count=floors_count,
units_count=units_count,
vacant_count=vacant_count,
occupied_count=occupied_count,
)
@app.route("/settings", endpoint="settings")
def settings_page():
floors = Floor.query.order_by(Floor.floor_number).all()
ctx = dict(all_settings())
ctx["floors"] = floors
return render_template("settings.html", **ctx)
@app.route("/settings/save", methods=["POST"])
@csrf_protect
def save_settings():
try:
for key in SETTING_KEYS:
if key in request.form:
set_setting(key, request.form.get(key))
db.session.commit()
flash("설정이 저장되었습니다.", "success")
except Exception as e: # noqa: BLE001 - 사용자에게 실패를 알려야 한다
db.session.rollback()
flash("설정 저장 실패: {}".format(e), "error")
return redirect(url_for("settings"))
@app.route("/settings/export")
def export_settings():
"""설정과 회계 이력을 포함한 전체 JSON 백업을 내보낸다."""
restriction = _tutorial_data_transfer_restriction()
if restriction:
return restriction
return jsonify(export_payload())
_TUTORIAL_DATA_TRANSFER_MESSAGE = (
"자유 연습 중에는 백업 내보내기와 복원을 사용할 수 없습니다. "
"연습을 종료한 뒤 실제 데이터 화면에서 이용해주세요."
)
def _tutorial_data_transfer_restriction():
"""연습 DB와 실제 백업 파일이 섞이지 않도록 데이터 이동을 차단한다."""
if app.config.get("TUTORIAL_MODE"):
return json_error(_TUTORIAL_DATA_TRANSFER_MESSAGE, status=403)
return None
def _create_safety_backup(reason):
"""위험한 변경 직전 현재 SQLite DB의 검증된 복원 지점을 만든다."""
if app.config.get("TUTORIAL_MODE"):
return None
from config import resolve_db_path
from db_backup import backup_database
database_path = resolve_db_path()
if database_path is None:
raise ValueError("현재 DB 연결 방식에서는 자동 파일 백업을 지원하지 않습니다.")
stamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
output = database_path.parent / "backups" / "{}_{}.db".format(reason, stamp)
return backup_database(output=output)
def _apply_full_restore(validated, backup_reason):
"""검증된 전체 백업을 자동 백업·정합성 검사와 함께 적용한다."""
backup_path = _create_safety_backup(backup_reason)
replace_all(validated["decoded"])
from db_validate import run_all_checks
failed = [check for check in run_all_checks() if not check.ok]
if failed:
raise BackupFormatError(
"복원 후 정합성 검사 실패: {}".format(", ".join(check.name for check in failed))
)
db.session.commit()
db.session.expire_all()
return backup_path
def _restore_preview_token(prepared, source=None):
return URLSafeTimedSerializer(app.secret_key, salt="restore-preview-v1").dumps({
"scope": prepared["scope"],
"backup": prepared["backup_digest"],
"current": prepared["current_digest"],
"source": source,
})
def _verify_restore_preview(prepared, token, source=None):
if not token:
raise BackupFormatError("복원 전에 데이터 미리보기를 다시 확인해주세요.")
try:
signed = URLSafeTimedSerializer(app.secret_key, salt="restore-preview-v1").loads(
token, max_age=600
)
except SignatureExpired:
raise BackupFormatError("복원 미리보기가 만료되었습니다. 다시 확인해주세요.")
except BadSignature:
raise BackupFormatError("복원 미리보기 정보가 올바르지 않습니다. 다시 확인해주세요.")
expected = {
"scope": prepared["scope"],
"backup": prepared["backup_digest"],
"current": prepared["current_digest"],
"source": source,
}
if signed != expected:
raise BackupFormatError(
"미리보기 이후 복원 범위·백업 파일 또는 현재 데이터가 변경되었습니다. "
"다시 확인해주세요."
)
def _restore_preview_response(prepared, message):
return {
"success": True,
"message": message,
"restore_scope": prepared["scope"],
"scope_label": prepared["scope_label"],
"affected_tables": prepared["affected_tables"],
"warnings": prepared["warnings"],
"current_counts": prepared["current_counts"],
"target_counts": prepared["target_counts"],
"backup_counts": prepared["target_counts"],
"backup_created_at": prepared["backup_created_at"],
}
_BACKUP_REASON_LABELS = {
"before_full_restore": "전체 백업 복원 전",
"before_automatic_restore": "자동 백업으로 되돌리기 전",
"before_partial_restore": "부분 복원 전",
"before_partial_automatic_restore": "자동 백업 부분 복원 전",
"before_floor_delete": "층 삭제 전",
"before_unit_delete": "세대 삭제 전",
"before_electric_overwrite": "전기요금 덮어쓰기 전",
"before_water_overwrite": "수도요금 덮어쓰기 전",
"before_electric_delete": "전기요금 삭제 전",
"before_water_delete": "수도요금 삭제 전",
"before_common_delete": "공동 공과금 삭제 전",
"before_invoice_delete": "정산서 삭제 전",
"before_payment_delete": "입금 내역 삭제 전",
}
@app.route("/settings/automatic-backups")
def automatic_backups():
"""설정 화면에서 선택할 수 있는 최근 자동 복원 지점을 반환한다."""
restriction = _tutorial_data_transfer_restriction()
if restriction:
return restriction
from db_backup import list_automatic_backups
try:
return jsonify({
"success": True,
"backups": [
{
"filename": item["filename"],
"reason": item["reason"],
"reason_label": _BACKUP_REASON_LABELS.get(item["reason"], "위험 작업 전"),
"created_at": item["created_at"].isoformat(timespec="seconds"),
"size": item["size"],
}
for item in list_automatic_backups()
],
})
except Exception as exc: # noqa: BLE001
return json_error("자동 백업 목록을 읽지 못했습니다: {}".format(exc))
@app.route("/settings/automatic-backups/preview", methods=["POST"])
@csrf_protect
def preview_automatic_backup():
"""선택한 자동 백업을 적용하지 않고 검증한다."""
restriction = _tutorial_data_transfer_restriction()
if restriction:
return restriction
from db_backup import resolve_automatic_backup
try:
data = request.get_json(silent=True) or {}
path = resolve_automatic_backup(data.get("filename"))
validated = validate_sqlite_backup(path)
prepared = prepare_restore(validated["payload"], data.get("restore_scope", "full"))
response = _restore_preview_response(prepared, "자동 백업 검사가 완료되었습니다.")
response["preview_token"] = _restore_preview_token(prepared, path.name)
return jsonify(response)
except Exception as exc: # noqa: BLE001
return json_error(str(exc))
@app.route("/settings/automatic-backups/restore", methods=["POST"])
@csrf_protect
def restore_automatic_backup():
"""자동 백업의 선택 묶음으로 현재 상태를 교체한다."""
restriction = _tutorial_data_transfer_restriction()
if restriction:
return restriction
from db_backup import resolve_automatic_backup
data = request.get_json(silent=True) or {}
if data.get("confirm_selected_replace") is not True and data.get("confirm_full_replace") is not True:
return json_error("선택 범위 교체 확인이 필요합니다.")
new_backup = None
try:
path = resolve_automatic_backup(data.get("filename"))
validated = validate_sqlite_backup(path)
prepared = prepare_restore(validated["payload"], data.get("restore_scope", "full"))
_verify_restore_preview(prepared, data.get("preview_token"), path.name)
reason = (
"before_automatic_restore"
if prepared["scope"] == "full"
else "before_partial_automatic_restore"
)
new_backup = _apply_full_restore(prepared["validated"], reason)
return jsonify({
"success": True,
"message": "선택한 자동 복원 지점의 {} 범위로 되돌렸습니다.".format(
prepared["scope_label"]
),
"restore_scope": prepared["scope"],
"restored_counts": prepared["target_counts"],
"automatic_backup": str(new_backup),
})
except Exception as exc: # noqa: BLE001
db.session.rollback()
return json_error(
"자동 백업 복원 실패: {}".format(exc),
automatic_backup=str(new_backup) if new_backup else None,
)
@app.route("/settings/import/preview", methods=["POST"])
@csrf_protect
def preview_import_settings():
"""복원 목표를 실제 DB와 분리된 임시 DB에서 검증한다."""
restriction = _tutorial_data_transfer_restriction()
if restriction:
return restriction
try:
payload = request.get_json(silent=True)
scope = payload.get("restore_scope", "full") if isinstance(payload, dict) else "full"
prepared = prepare_restore(payload, scope)
response = _restore_preview_response(prepared, "복원 목표 검증이 완료되었습니다.")
response["preview_token"] = _restore_preview_token(prepared)
return jsonify(response)
except BackupFormatError as exc:
return json_error(str(exc))
@app.route("/settings/import", methods=["POST"])
@csrf_protect
def import_settings():
"""현재 DB의 선택 묶음을 검증된 백업 내용으로 교체한다."""
restriction = _tutorial_data_transfer_restriction()
if restriction:
return restriction
data = request.get_json(silent=True)
if not isinstance(data, dict):
return json_error("JSON 본문을 해석할 수 없습니다.")
if data.get("confirm_selected_replace") is not True and data.get("confirm_full_replace") is not True:
return json_error("선택 범위 교체 확인이 필요합니다.")
backup_path = None
try:
prepared = prepare_restore(data, data.get("restore_scope", "full"))
_verify_restore_preview(prepared, data.get("preview_token"))
reason = "before_full_restore" if prepared["scope"] == "full" else "before_partial_restore"
backup_path = _apply_full_restore(prepared["validated"], reason)
return jsonify({
"success": True,
"message": "{} 범위를 백업 내용으로 복원했습니다.".format(
prepared["scope_label"]
),
"restore_scope": prepared["scope"],
"restored_counts": prepared["target_counts"],
"automatic_backup": str(backup_path),
})
except Exception as e: # noqa: BLE001
db.session.rollback()
return json_error(
"복원 실패: {}".format(e),
automatic_backup=str(backup_path) if backup_path else None,
)
@app.route("/floors/add", methods=["POST"])
@csrf_protect
def add_floor():
try:
floor_number_str = request.form.get("floor_number", "").strip()
if not floor_number_str:
return json_error("층 번호를 입력해주세요.")
floor_number = to_int(floor_number_str, None)
if floor_number is None: