Repository navigation
Expand file tree
/
Copy pathdb_validate.py
More file actions
614 lines (554 loc) · 21.7 KB
/
Copy pathdb_validate.py
File metadata and controls
614 lines (554 loc) · 21.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
"""DB 정합성 검증.
두 층위를 검사한다.
1. SQLite 엔진 수준 — ``PRAGMA foreign_key_check`` / ``PRAGMA integrity_check``
2. 애플리케이션 도메인 수준 — 스키마 제약만으로는 잡히지 않는 규칙
실행::
flask check-db
"""
from decimal import Decimal
from sqlalchemy import text
from extensions import db
from models import (
CommonBill,
CommonBillDetail,
ElectricBill,
ElectricBillDetail,
ElectricBillMonth,
FinalInvoice,
FinalInvoiceCharge,
InvoiceCombinationItem,
Payment,
WaterBill,
WaterBillDetail,
)
SNAPSHOT_KEYS = (
"unit_id",
"floor_id",
"floor_number",
"floor_name",
"unit_name",
"electric_welfare",
"electric_voucher",
"has_tv",
"water_welfare",
"residents_count",
"is_vacant",
)
class Check:
"""검사 하나의 결과."""
def __init__(self, name, ok, detail=None, rows=None):
self.name = name
self.ok = ok
self.detail = detail
self.rows = rows or []
def as_dict(self):
return {
"name": self.name,
"ok": self.ok,
"detail": self.detail,
"rows": self.rows[:50],
"row_count": len(self.rows),
}
# ---------------------------------------------------------------------------
# 엔진 수준
# ---------------------------------------------------------------------------
def check_foreign_keys():
rows = db.session.execute(text("PRAGMA foreign_key_check")).fetchall()
return Check(
"foreign_key_check",
not rows,
"참조 무결성 위반 {}건".format(len(rows)) if rows else "위반 없음",
[dict(zip(("table", "rowid", "parent", "fkid"), r)) for r in rows],
)
def check_integrity():
result = db.session.execute(text("PRAGMA integrity_check")).scalar()
return Check("integrity_check", result == "ok", result)
def check_foreign_keys_enabled():
value = db.session.execute(text("PRAGMA foreign_keys")).scalar()
return Check(
"foreign_keys_enabled",
bool(value),
"PRAGMA foreign_keys = {}".format(value),
)
# ---------------------------------------------------------------------------
# 도메인 수준
# ---------------------------------------------------------------------------
def check_billing_month_normalized():
"""모든 billing_month 가 그 달 1일인지."""
bad = []
for table in (
"electric_bills",
"electric_bill_months",
"water_bills",
"common_bills",
"invoice_combination_items",
):
rows = db.session.execute(
text(
"SELECT id, billing_month FROM {} "
"WHERE substr(billing_month, 9, 2) <> '01'".format(table)
)
).fetchall()
bad.extend({"table": table, "id": r[0], "billing_month": r[1]} for r in rows)
return Check(
"billing_month_normalized",
not bad,
"정규화되지 않은 정산월 {}건".format(len(bad)) if bad else "전부 1일",
bad,
)
def check_polymorphic_items():
"""invoice_combination_items 의 item_type 과 FK 가 일치하는지."""
bad = []
for item in InvoiceCombinationItem.query.all():
fks = [item.electric_bill_id, item.water_bill_id, item.common_bill_id]
filled = [f for f in fks if f is not None]
expected = {"ELECTRIC": 0, "WATER": 1, "COMMON": 2}.get(item.item_type)
if len(filled) != 1 or expected is None or fks[expected] is None:
bad.append(
{
"id": item.id,
"item_type": item.item_type,
"electric_bill_id": item.electric_bill_id,
"water_bill_id": item.water_bill_id,
"common_bill_id": item.common_bill_id,
}
)
return Check(
"invoice_item_polymorphic_reference",
not bad,
"다형 참조 위반 {}건".format(len(bad)) if bad else "위반 없음",
bad,
)
def check_snapshots():
"""unit_snapshot 이 필수 키를 모두 갖고 있는지."""
bad = []
for model, label in (
(ElectricBillDetail, "electric_bill_details"),
(WaterBillDetail, "water_bill_details"),
(CommonBillDetail, "common_bill_details"),
):
for row in model.query.all():
snapshot = row.unit_snapshot
if snapshot is None:
bad.append({"table": label, "id": row.id, "issue": "snapshot_missing"})
continue
if not isinstance(snapshot, dict):
bad.append({"table": label, "id": row.id, "issue": "snapshot_not_object"})
continue
missing = [k for k in SNAPSHOT_KEYS if k not in snapshot]
if missing:
bad.append(
{
"table": label,
"id": row.id,
"issue": "missing_keys",
"keys": missing,
}
)
return Check(
"unit_snapshot_complete",
not bad,
"스냅샷 문제 {}건".format(len(bad)) if bad else "전부 정상",
bad,
)
def check_final_invoice_snapshots():
"""발행 정산서가 현재 세대 마스터와 독립된 수신자 정보를 갖는지."""
bad = []
for row in FinalInvoice.query.all():
missing = []
if not row.unit_name_snapshot:
missing.append("unit_name_snapshot")
if row.floor_number_snapshot is None:
missing.append("floor_number_snapshot")
if row.floor_name_snapshot is None:
missing.append("floor_name_snapshot")
if row.unit_profile_memo_snapshot is None:
missing.append("unit_profile_memo_snapshot")
if not row.snapshot_source:
missing.append("snapshot_source")
if missing:
bad.append({"final_invoice_id": row.id, "missing": missing})
return Check(
"final_invoice_snapshot_complete",
not bad,
"정산서 스냅샷 문제 {}건".format(len(bad)) if bad else "전부 정상",
bad,
)
def check_allocation_reconciliation():
"""입력 총액·할인과 세대별 배분 중간값의 합이 일치하는지."""
bad = []
tolerance = Decimal("0.05")
for bill in ElectricBill.query.all():
base_total = sum((row.base_amount for row in bill.details), Decimal(0))
welfare_total = sum((row.welfare_discount for row in bill.details), Decimal(0))
voucher_total = sum((row.voucher_discount for row in bill.details), Decimal(0))
expected_base = Decimal(bill.total_amount + bill.welfare_discount + bill.voucher_discount)
if abs(base_total - expected_base) > tolerance or welfare_total != Decimal(bill.welfare_discount) or voucher_total != Decimal(bill.voucher_discount):
bad.append({
"table": "electric_bills", "id": bill.id,
"base_total": str(base_total), "expected_base": str(expected_base),
"welfare_total": str(welfare_total), "voucher_total": str(voucher_total),
})
for row in bill.details:
discount = row.welfare_discount + row.voucher_discount
if bill.discount_tv_policy == "TV_PROTECTED":
expected_final = max(row.base_amount - discount, Decimal(0)) + row.tv_fee
else:
expected_final = max(
row.base_amount - discount + row.tv_fee, Decimal(0)
)
if abs(row.final_amount - expected_final) > tolerance:
bad.append({
"table": "electric_bill_details",
"id": row.id,
"bill_id": bill.id,
"discount_tv_policy": bill.discount_tv_policy,
"final_amount": str(row.final_amount),
"expected_final": str(expected_final),
})
for bill in WaterBillDetail.query.with_entities(WaterBillDetail.water_bill_id).distinct():
identifier = bill[0]
parent = db.session.get(WaterBill, identifier)
rows = WaterBillDetail.query.filter_by(water_bill_id=identifier, is_excluded=False).all()
base_total = sum((row.base_amount for row in rows), Decimal(0))
discount_total = sum((row.welfare_discount for row in rows), Decimal(0))
expected_base = Decimal(parent.total_amount + parent.welfare_discount_total)
if abs(base_total - expected_base) > tolerance or discount_total != Decimal(parent.welfare_discount_total):
bad.append({
"table": "water_bills", "id": identifier,
"base_total": str(base_total), "expected_base": str(expected_base),
"discount_total": str(discount_total),
})
for row in WaterBillDetail.query.filter_by(water_bill_id=identifier).all():
expected_final = max(
row.base_amount - row.welfare_discount, Decimal(0)
)
if abs(row.final_amount - expected_final) > tolerance:
bad.append({
"table": "water_bill_details",
"id": row.id,
"bill_id": identifier,
"final_amount": str(row.final_amount),
"expected_final": str(expected_final),
})
for bill in CommonBill.query.all():
amount_total = sum((row.amount for row in bill.details), Decimal(0))
if abs(amount_total - Decimal(bill.total_amount)) > tolerance:
bad.append({
"table": "common_bills", "id": bill.id,
"amount_total": str(amount_total), "expected": str(bill.total_amount),
})
return Check(
"allocation_totals_reconciled",
not bad,
"배분 합계 불일치 {}건".format(len(bad)) if bad else "전부 일치",
bad,
)
def check_source_unique_indexes():
expected = {
"uq_invoice_items_electric_bill_once",
"uq_invoice_items_water_bill_once",
"uq_invoice_items_common_bill_once",
}
rows = db.session.execute(text("PRAGMA index_list('invoice_combination_items')")).fetchall()
found = {row[1] for row in rows if row[2] == 1}
missing = sorted(expected - found)
return Check(
"invoice_source_unique_indexes",
not missing,
"누락된 고유 인덱스: {}".format(", ".join(missing)) if missing else "전부 존재",
[{"index": name} for name in missing],
)
def check_charged_amount_rounding():
"""charged_amount 가 10원 단위인지 (10원 올림 정책)."""
bad = []
for model, label in (
(ElectricBillDetail, "electric_bill_details"),
(WaterBillDetail, "water_bill_details"),
(CommonBillDetail, "common_bill_details"),
):
for row in model.query.all():
if row.charged_amount % 10 != 0:
bad.append(
{"table": label, "id": row.id, "charged_amount": row.charged_amount}
)
return Check(
"charged_amount_multiple_of_10",
not bad,
"10원 단위가 아닌 청구액 {}건".format(len(bad)) if bad else "전부 10원 단위",
bad,
)
def check_final_invoice_totals():
"""final_invoices.total_amount 가 구성요소 합과 일치하는지.
total = electric + water + common + Σ(모든 기타 항목, 이월 포함)
"""
bad = []
for invoice in FinalInvoice.query.all():
expected = (
invoice.electric_amount
+ invoice.water_amount
+ invoice.common_amount
+ sum(c.amount for c in invoice.charges)
)
if invoice.total_amount != expected:
bad.append(
{
"final_invoice_id": invoice.id,
"stored_total": invoice.total_amount,
"computed_total": expected,
"difference": invoice.total_amount - expected,
}
)
return Check(
"final_invoice_total_consistent",
not bad,
"청구서 합계 불일치 {}건".format(len(bad)) if bad else "전부 일치",
bad,
)
def check_duplicate_invoice_sources():
"""같은 고지 항목이 여러 번 청구된 과거 기록을 찾는다."""
bad = []
for item_type, column in (
("ELECTRIC", "electric_bill_id"),
("WATER", "water_bill_id"),
("COMMON", "common_bill_id"),
):
rows = db.session.execute(text(
"SELECT {0}, COUNT(*) FROM invoice_combination_items "
"WHERE {0} IS NOT NULL GROUP BY {0} HAVING COUNT(*) > 1".format(column)
)).fetchall()
bad.extend(
{"type": item_type, "bill_id": bill_id, "use_count": count}
for bill_id, count in rows
)
return Check(
"invoice_source_used_once",
not bad,
"중복 청구된 고지 항목 {}건".format(len(bad)) if bad else "중복 없음",
bad,
)
def check_payment_invoice_pairs():
"""입금이 실제 해당 세대의 정산서에 연결되어 있는지 확인한다."""
rows = db.session.execute(text(
"SELECT p.id, p.combination_id, p.unit_id FROM payments p "
"LEFT JOIN final_invoices f ON f.combination_id = p.combination_id "
"AND f.unit_id = p.unit_id WHERE f.id IS NULL"
)).fetchall()
bad = [
{"payment_id": payment_id, "combination_id": combination_id, "unit_id": unit_id}
for payment_id, combination_id, unit_id in rows
]
return Check(
"payments_have_matching_invoice",
not bad,
"청구서와 연결되지 않은 입금 {}건".format(len(bad)) if bad else "전부 연결됨",
bad,
)
def check_negative_electric_usage():
bad = [
{"detail_id": row.id, "electric_bill_id": row.electric_bill_id,
"unit_id": row.unit_id, "usage_amount": str(row.usage_amount)}
for row in ElectricBillDetail.query.all() if row.usage_amount < 0
]
return Check(
"electric_usage_non_negative",
not bad,
"음수 전기 사용량 {}건".format(len(bad)) if bad else "전부 0 이상",
bad,
)
def check_common_bill_allocations():
"""이전 화면 오류로 생성된 0원 고지와 배분 누락을 찾는다."""
bad = [
{"common_bill_id": bill.id, "total_amount": bill.total_amount,
"detail_count": len(bill.details)}
for bill in CommonBill.query.all()
if bill.total_amount <= 0 or not bill.details
]
return Check(
"common_bills_allocated",
not bad,
"0원 또는 배분 누락 공동 공과금 {}건".format(len(bad)) if bad else "전부 배분됨",
bad,
)
def check_electric_month_count():
"""billing_months_count 가 실제 고지월 행 수와 일치하는지."""
bad = []
for bill in ElectricBill.query.all():
actual = ElectricBillMonth.query.filter_by(electric_bill_id=bill.id).count()
if bill.billing_months_count != actual:
bad.append(
{
"electric_bill_id": bill.id,
"billing_months_count": bill.billing_months_count,
"actual_month_rows": actual,
}
)
return Check(
"electric_billing_months_count",
not bad,
"고지월 개수 불일치 {}건".format(len(bad)) if bad else "전부 일치",
bad,
)
def check_orphans():
"""FK 로 막히지만, 과거 데이터가 이전되어 온 경우를 위해 한 번 더 확인한다."""
queries = {
"orphan_electric_bill_months": (
"SELECT m.id FROM electric_bill_months m "
"LEFT JOIN electric_bills b ON b.id = m.electric_bill_id "
"WHERE b.id IS NULL"
),
"orphan_final_invoice_charges": (
"SELECT c.id FROM final_invoice_charges c "
"LEFT JOIN final_invoices f ON f.id = c.final_invoice_id "
"WHERE f.id IS NULL"
),
"orphan_payments": (
"SELECT p.id FROM payments p "
"LEFT JOIN invoice_combinations c ON c.id = p.combination_id "
"WHERE c.id IS NULL"
),
}
bad = []
for name, sql in queries.items():
rows = db.session.execute(text(sql)).fetchall()
bad.extend({"check": name, "id": r[0]} for r in rows)
return Check(
"no_orphan_rows",
not bad,
"고아 레코드 {}건".format(len(bad)) if bad else "고아 레코드 없음",
bad,
)
def check_carryover_flags():
"""이월 항목이 명시적 플래그로 관리되고 있는지 (참고용 리포트).
문자열 규칙과 플래그가 어긋나는 항목을 보고한다.
이는 오류가 아니라 **사후 검토 대상**이다. 사용자가 의도적으로
'환급' 이라는 이름의 일반 청구를 만들었을 수 있기 때문이다.
"""
legacy_keywords = ("미납", "초과납부", "환급", "이월")
mismatched = []
for charge in FinalInvoiceCharge.query.all():
looks_carryover = any(k in (charge.description or "") for k in legacy_keywords)
if looks_carryover != bool(charge.is_carryover):
mismatched.append(
{
"charge_id": charge.id,
"final_invoice_id": charge.final_invoice_id,
"description": charge.description,
"is_carryover": bool(charge.is_carryover),
"legacy_keyword_match": looks_carryover,
}
)
return Check(
"carryover_flag_review",
True, # 정보성 검사. 실패로 처리하지 않는다.
"문자열 규칙과 플래그가 다른 항목 {}건 (검토 대상)".format(len(mismatched))
if mismatched
else "문자열 규칙과 플래그가 모두 일치",
mismatched,
)
def check_money_columns_are_integers():
"""Money 컬럼이 실제로 정수로 저장되어 있는지."""
bad = []
checks = (
("electric_bills", ("total_amount", "welfare_discount", "voucher_discount", "tv_fee_total")),
("electric_bill_months", ("amount", "welfare_discount", "voucher_discount", "tv_fee")),
("electric_bill_details", ("charged_amount",)),
("water_bills", ("total_amount", "welfare_discount_total")),
("water_bill_details", ("charged_amount",)),
("common_bills", ("total_amount",)),
("common_bill_details", ("charged_amount",)),
("final_invoices", ("electric_amount", "water_amount", "common_amount", "total_amount")),
("final_invoice_charges", ("amount",)),
("payments", ("payment_amount",)),
)
for table, columns in checks:
for column in columns:
rows = db.session.execute(
text(
"SELECT id, {col} FROM {tbl} "
"WHERE typeof({col}) NOT IN ('integer', 'null')".format(
col=column, tbl=table
)
)
).fetchall()
bad.extend(
{"table": table, "column": column, "id": r[0], "value": r[1]} for r in rows
)
return Check(
"money_columns_integer",
not bad,
"정수가 아닌 금액 {}건".format(len(bad)) if bad else "전부 정수 저장",
bad,
)
def check_decimal_columns_parse():
"""ExactDecimal 컬럼이 Decimal 로 파싱되는지."""
bad = []
checks = (
("electric_readings", ("previous_reading", "current_reading")),
(
"electric_bill_details",
("usage_amount", "base_amount", "welfare_discount", "voucher_discount", "tv_fee", "final_amount"),
),
("water_bill_details", ("base_amount", "welfare_discount", "final_amount")),
("common_bill_details", ("amount",)),
)
for table, columns in checks:
for column in columns:
rows = db.session.execute(
text("SELECT id, {col} FROM {tbl}".format(col=column, tbl=table))
).fetchall()
for row_id, value in rows:
if value is None:
continue
try:
Decimal(str(value))
except Exception: # noqa: BLE001
bad.append(
{"table": table, "column": column, "id": row_id, "value": value}
)
return Check(
"decimal_columns_parseable",
not bad,
"파싱 불가 값 {}건".format(len(bad)) if bad else "전부 파싱 가능",
bad,
)
ALL_CHECKS = (
check_foreign_keys_enabled,
check_integrity,
check_foreign_keys,
check_orphans,
check_billing_month_normalized,
check_polymorphic_items,
check_snapshots,
check_final_invoice_snapshots,
check_source_unique_indexes,
check_allocation_reconciliation,
check_charged_amount_rounding,
check_final_invoice_totals,
check_duplicate_invoice_sources,
check_payment_invoice_pairs,
check_negative_electric_usage,
check_common_bill_allocations,
check_electric_month_count,
check_money_columns_are_integers,
check_decimal_columns_parse,
check_carryover_flags,
)
def run_all_checks():
return [fn() for fn in ALL_CHECKS]
def format_report(checks):
lines = []
failed = 0
for check in checks:
mark = "OK " if check.ok else "FAIL"
if not check.ok:
failed += 1
lines.append("[{}] {} — {}".format(mark, check.name, check.detail))
if not check.ok:
for row in check.rows[:10]:
lines.append(" {}".format(row))
if len(check.rows) > 10:
lines.append(" ... 외 {}건".format(len(check.rows) - 10))
lines.append("")
lines.append("검사 {}건 중 {}건 실패".format(len(checks), failed))
return "\n".join(lines)