라벨 자동할당 로직 임시 커밋
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
package com.kamco.cd.kamcoback.label.service;
|
||||
|
||||
import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.Sheet;
|
||||
import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.TargetUser;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class LabelAllocateService {
|
||||
|
||||
public static void allocate(List<Sheet> sheets, List<TargetUser> targetUsers) {
|
||||
|
||||
// 1️⃣ 실제 도엽 기준 할당
|
||||
allocateSheets(sheets, targetUsers);
|
||||
|
||||
// 2️⃣ 전체 부족분 비율 계산
|
||||
distributeShortage(targetUsers); //항상 마지막에 한 번만 호출해야함
|
||||
|
||||
}
|
||||
|
||||
public static void allocateSheets(
|
||||
List<Sheet> sheets,
|
||||
List<TargetUser> targets
|
||||
) {
|
||||
// 도엽 큰 것부터 (선택 사항)
|
||||
sheets.sort(Comparator.comparingInt(Sheet::getCount).reversed());
|
||||
|
||||
for (TargetUser target : targets) {
|
||||
Iterator<Sheet> it = sheets.iterator();
|
||||
|
||||
while (it.hasNext() && target.getRemainDemand() > 0) {
|
||||
Sheet sheet = it.next();
|
||||
|
||||
int assignable = Math.min(
|
||||
sheet.getCount(),
|
||||
target.getRemainDemand()
|
||||
);
|
||||
|
||||
if (assignable > 0) {
|
||||
target.assign(sheet.getSheetId(), assignable);
|
||||
sheet.decrease(assignable);
|
||||
}
|
||||
|
||||
if (sheet.getCount() == 0) {
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void distributeShortage(List<TargetUser> targets) {
|
||||
|
||||
int totalDemand = targets.stream()
|
||||
.mapToInt(TargetUser::getDemand)
|
||||
.sum();
|
||||
|
||||
int totalAllocated = targets.stream()
|
||||
.mapToInt(t -> t.getAllocated())
|
||||
.sum();
|
||||
|
||||
int shortage = totalDemand - totalAllocated;
|
||||
|
||||
if (shortage <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
int distributed = 0;
|
||||
|
||||
for (int i = 0; i < targets.size(); i++) {
|
||||
TargetUser t = targets.get(i);
|
||||
|
||||
// 마지막 타겟이 나머지 가져가게 (반올림 오차 방지)
|
||||
int share;
|
||||
if (i == targets.size() - 1) {
|
||||
share = shortage - distributed;
|
||||
} else {
|
||||
double ratio = (double) t.getDemand() / totalDemand;
|
||||
share = (int) Math.round(shortage * ratio);
|
||||
distributed += share;
|
||||
}
|
||||
|
||||
t.setShortage(share);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user