Repository navigation
Expand file tree
/
Copy pathcalculation_service.py
More file actions
324 lines (287 loc) · 12.2 KB
/
Copy pathcalculation_service.py
File metadata and controls
324 lines (287 loc) · 12.2 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
"""요금 배분의 순수 계산 엔진.
미리보기와 실제 저장이 같은 함수를 사용하도록 DB 쓰기와 계산을 분리한다.
모든 분배는 1전(0.01원) 단위까지 합계가 정확히 맞도록 나머지를 안정적인
세대 ID 순서로 배분한다. 최종 청구액만 기존 정책대로 10원 단위 올림한다.
"""
from decimal import Decimal, ROUND_DOWN
CENT = Decimal("0.01")
class AllocationError(ValueError):
"""입력값으로 유효한 배분을 만들 수 없을 때 발생한다."""
def as_decimal(value):
if isinstance(value, Decimal):
return value
return Decimal(str(value or 0))
def round_up_to_10(amount):
value = as_decimal(amount)
if value <= 0:
return 0
return int(((value + Decimal("9.999999999")) // 10) * 10)
def split_exact(total, weighted_ids):
"""``total``을 ``[(id, weight)]``에 비례해 정확히 나눈다.
결과 합계는 소수 둘째 자리에서 항상 입력 합계와 일치한다. 동일한 잔여
소수점이면 작은 세대 ID가 먼저 0.01원을 받으므로 실행마다 결과가 같다.
"""
total = as_decimal(total).quantize(CENT)
entries = [(identifier, as_decimal(weight)) for identifier, weight in weighted_ids]
if not entries:
if total != 0:
raise AllocationError("배분할 세대가 없습니다.")
return {}
if total < 0:
raise AllocationError("배분 금액은 음수일 수 없습니다.")
weight_total = sum((weight for _, weight in entries), Decimal(0))
if weight_total <= 0:
entries = [(identifier, Decimal(1)) for identifier, _ in entries]
weight_total = Decimal(len(entries))
raw = {
identifier: total * weight / weight_total
for identifier, weight in entries
}
result = {
identifier: value.quantize(CENT, rounding=ROUND_DOWN)
for identifier, value in raw.items()
}
remaining_cents = int(
((total - sum(result.values(), Decimal(0))) / CENT).to_integral_value()
)
order = sorted(
entries,
key=lambda entry: (-(raw[entry[0]] - result[entry[0]]), entry[0]),
)
for index in range(remaining_cents):
result[order[index % len(order)][0]] += CENT
return result
def _discount_map(total_input, units, flag_name, configured_per_unit, month_count=1):
"""할인 수혜 세대와 적용 방식을 결정한다.
입력 할인액이 있으면 특정 대상이 존재할 때는 대상에게, 대상이 하나도
없을 때는 정산 대상 전체에게 균등 배분한다. 입력액이 0이면 기존 정책대로
설정 단가를 특정 대상 세대에만 적용한다.
"""
total_input = as_decimal(total_input)
target_units = [unit for unit in units if bool(getattr(unit, flag_name))]
if total_input > 0:
recipients = target_units or list(units)
mode = "targeted" if target_units else "floor_equal"
return split_exact(total_input, [(unit.id, 1) for unit in recipients]), mode
if not target_units:
return {unit.id: Decimal(0) for unit in units}, "none"
per_unit = as_decimal(configured_per_unit) * month_count
return {unit.id: per_unit for unit in target_units}, "configured"
def allocate_electric(
units,
readings,
*,
total_amount,
welfare_discount_input,
voucher_discount_input,
tv_fee_total,
tv_distribution_mode,
month_count,
configured_tv_fee,
configured_welfare_discount,
configured_voucher_discount,
discount_tv_policy="COMBINED_FLOOR_ZERO",
):
if not units:
raise AllocationError("전기요금을 배분할 재실 세대가 없습니다.")
usage = {}
for unit in units:
previous, current = readings[unit.id]
previous = as_decimal(previous)
current = as_decimal(current)
if current < previous:
raise AllocationError(
"{}의 현재 검침값이 이전 검침값보다 작습니다.".format(unit.unit_name)
)
usage[unit.id] = current - previous
welfare, welfare_mode = _discount_map(
welfare_discount_input,
units,
"electric_welfare",
configured_welfare_discount,
month_count,
)
voucher, voucher_mode = _discount_map(
voucher_discount_input,
units,
"electric_voucher",
configured_voucher_discount,
month_count,
)
welfare_total = sum(welfare.values(), Decimal(0))
voucher_total = sum(voucher.values(), Decimal(0))
gross_amount = as_decimal(total_amount) + welfare_total + voucher_total
total_usage = sum(usage.values(), Decimal(0))
zero_usage_fallback = total_usage <= 0
weights = [(unit.id, usage[unit.id] if total_usage > 0 else 1) for unit in units]
base = split_exact(gross_amount, weights)
if tv_distribution_mode == "EQUAL":
tv = split_exact(tv_fee_total, [(unit.id, 1) for unit in units])
else:
tv_per_unit = as_decimal(configured_tv_fee) * month_count
tv = {
unit.id: tv_per_unit if bool(unit.has_tv) else Decimal(0)
for unit in units
}
if discount_tv_policy not in ("COMBINED_FLOOR_ZERO", "TV_PROTECTED"):
raise AllocationError("할인 초과 시 TV 수신료 처리 방식이 올바르지 않습니다.")
details = []
overflow_rows = []
for unit in sorted(units, key=lambda row: row.id):
discount = welfare.get(unit.id, 0) + voucher.get(unit.id, 0)
if discount_tv_policy == "TV_PROTECTED":
electric_after_discount = base[unit.id] - discount
unused_discount = max(-electric_after_discount, Decimal(0))
final_amount = max(electric_after_discount, Decimal(0)) + tv[unit.id]
else:
combined_after_discount = base[unit.id] - discount + tv[unit.id]
unused_discount = max(-combined_after_discount, Decimal(0))
final_amount = max(combined_after_discount, Decimal(0))
if unused_discount > 0:
overflow_rows.append((unit.unit_name, unused_discount))
details.append(
{
"unit": unit,
"usage_amount": usage[unit.id],
"base_amount": base[unit.id],
"welfare_discount": welfare.get(unit.id, Decimal(0)),
"voucher_discount": voucher.get(unit.id, Decimal(0)),
"tv_fee": tv[unit.id],
"unused_discount": unused_discount,
"final_amount": final_amount,
"charged_amount": round_up_to_10(final_amount),
}
)
warnings = []
if welfare_mode == "floor_equal":
warnings.append("특정 복지할인 대상이 없어 정산 대상 세대 전체에 균등 배분했습니다.")
if voucher_mode == "floor_equal":
warnings.append("특정 바우처 대상이 없어 정산 대상 세대 전체에 균등 배분했습니다.")
if zero_usage_fallback:
warnings.append("전체 사용량이 0이므로 정산 대상 세대에 균등 배분했습니다.")
for unit_name, unused_discount in overflow_rows:
warnings.append(
"{}의 할인 중 {:,.2f}원은 해당 세대 요금을 0원으로 만든 뒤 "
"남아 다른 세대에 재배분하지 않았습니다.".format(
unit_name, unused_discount
)
)
return _result(details, warnings, {
"welfare_discount_total": welfare_total,
"voucher_discount_total": voucher_total,
"welfare_distribution": welfare_mode,
"voucher_distribution": voucher_mode,
"zero_usage_fallback": zero_usage_fallback,
"discount_tv_policy": discount_tv_policy,
"unused_discount_total": sum(
(amount for _, amount in overflow_rows), Decimal(0)
),
})
def allocate_water(
all_units,
included_units,
*,
total_amount,
welfare_discount_input,
configured_welfare_discount,
):
if not all_units:
raise AllocationError("수도요금을 배분할 재실 세대가 없습니다.")
if not included_units and as_decimal(total_amount) > 0:
raise AllocationError("모든 세대를 제외하면 수도요금을 배분할 수 없습니다.")
welfare, welfare_mode = _discount_map(
welfare_discount_input,
included_units,
"water_welfare",
configured_welfare_discount,
)
welfare_total = sum(welfare.values(), Decimal(0))
gross_amount = as_decimal(total_amount) + welfare_total
total_residents = sum((unit.residents_count for unit in included_units), 0)
zero_residents_fallback = bool(included_units) and total_residents <= 0
weights = [
(unit.id, unit.residents_count if total_residents > 0 else 1)
for unit in included_units
]
base = split_exact(gross_amount, weights)
included_ids = {unit.id for unit in included_units}
details = []
overflow_rows = []
for unit in sorted(all_units, key=lambda row: row.id):
if unit.id not in included_ids:
details.append({
"unit": unit,
"base_amount": Decimal(0),
"welfare_discount": Decimal(0),
"final_amount": Decimal(0),
"charged_amount": 0,
"is_excluded": True,
})
continue
after_discount = base[unit.id] - welfare.get(unit.id, 0)
unused_discount = max(-after_discount, Decimal(0))
final_amount = max(after_discount, Decimal(0))
if unused_discount > 0:
overflow_rows.append((unit.unit_name, unused_discount))
details.append({
"unit": unit,
"base_amount": base[unit.id],
"welfare_discount": welfare.get(unit.id, Decimal(0)),
"unused_discount": unused_discount,
"final_amount": final_amount,
"charged_amount": round_up_to_10(final_amount),
"is_excluded": False,
})
warnings = []
if welfare_mode == "floor_equal":
warnings.append("특정 수도 복지할인 대상이 없어 정산 대상 세대 전체에 균등 배분했습니다.")
if zero_residents_fallback:
warnings.append("정산 대상의 거주 인원이 모두 0명이므로 세대 균등으로 배분했습니다.")
for unit_name, unused_discount in overflow_rows:
warnings.append(
"{}의 할인 중 {:,.2f}원은 해당 세대 요금을 0원으로 만든 뒤 "
"남아 다른 세대에 재배분하지 않았습니다.".format(
unit_name, unused_discount
)
)
return _result(details, warnings, {
"welfare_discount_total": welfare_total,
"welfare_distribution": welfare_mode,
"zero_residents_fallback": zero_residents_fallback,
"unused_discount_total": sum(
(amount for _, amount in overflow_rows), Decimal(0)
),
})
def allocate_common(units, *, total_amount, distribution_method):
if not units:
raise AllocationError("배분할 재실 세대가 없습니다.")
total_residents = sum((unit.residents_count for unit in units), 0)
fallback = distribution_method == "BY_RESIDENTS" and total_residents <= 0
weights = [
(unit.id, unit.residents_count if distribution_method == "BY_RESIDENTS" and total_residents > 0 else 1)
for unit in units
]
amounts = split_exact(total_amount, weights)
details = [
{
"unit": unit,
"amount": amounts[unit.id],
"final_amount": amounts[unit.id],
"charged_amount": round_up_to_10(amounts[unit.id]),
}
for unit in sorted(units, key=lambda row: row.id)
]
warnings = ["거주 인원이 모두 0명이므로 세대 균등으로 배분했습니다."] if fallback else []
return _result(details, warnings, {"zero_residents_fallback": fallback})
def _result(details, warnings, extra):
final_total = sum((row["final_amount"] for row in details), Decimal(0))
charged_total = sum((row["charged_amount"] for row in details), 0)
result = {
"details": details,
"warnings": warnings,
"final_total": final_total,
"charged_total": charged_total,
"rounding_difference": as_decimal(charged_total) - final_total,
}
result.update(extra)
return result