419 lines
14 KiB
PHP
419 lines
14 KiB
PHP
<?php
|
|
|
|
namespace App\Business\KukaPostingBase;
|
|
|
|
use InvalidArgumentException;
|
|
|
|
/**
|
|
* 按料号分配整月过账金额,并在每个料号内按发货日期优先选行。
|
|
*/
|
|
class KukaPostingAmountSelection
|
|
{
|
|
/**
|
|
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
|
|
* @return array{
|
|
* exact: bool,
|
|
* target_cents: int,
|
|
* total_cents: int,
|
|
* selected_cents: int,
|
|
* difference_cents: int,
|
|
* selected_ids: list<int>,
|
|
* selected_rows: int,
|
|
* selected_materials: int,
|
|
* allocations: list<array{
|
|
* material_number: string,
|
|
* total_cents: int,
|
|
* allocated_cents: int,
|
|
* selected_cents: int,
|
|
* selected_rows: int,
|
|
* row_count: int
|
|
* }>
|
|
* }
|
|
*/
|
|
public function select(array $groups, int $targetCents): array
|
|
{
|
|
if ($targetCents <= 0) {
|
|
throw new InvalidArgumentException('整月过账金额必须大于 0。');
|
|
}
|
|
|
|
$groups = $this->normalizeGroups($groups);
|
|
if ($groups === []) {
|
|
throw new InvalidArgumentException('当前账期没有可用于过账的料号和发货金额。');
|
|
}
|
|
|
|
$totalCents = 0;
|
|
$minimumCents = 0;
|
|
foreach ($groups as $rows) {
|
|
$totalCents += array_sum(array_column($rows, 'amount_cents'));
|
|
$minimumCents += (int) $rows[0]['amount_cents'];
|
|
}
|
|
if ($targetCents > $totalCents) {
|
|
throw new InvalidArgumentException('整月过账金额不能大于可计算发货金额合计。');
|
|
}
|
|
|
|
$allocations = $this->proportionalAllocations($groups, $targetCents, $minimumCents);
|
|
$selected = [];
|
|
foreach ($groups as $materialNumber => $rows) {
|
|
$allocation = $allocations[$materialNumber];
|
|
$prefixCents = 0;
|
|
$bestCount = 1;
|
|
$bestDifference = PHP_INT_MAX;
|
|
foreach ($rows as $index => $row) {
|
|
$prefixCents += (int) $row['amount_cents'];
|
|
$difference = abs($allocation - $prefixCents);
|
|
if ($difference < $bestDifference) {
|
|
$bestDifference = $difference;
|
|
$bestCount = $index + 1;
|
|
}
|
|
}
|
|
for ($index = 0; $index < $bestCount; $index++) {
|
|
$selected[(int) $rows[$index]['id']] = true;
|
|
}
|
|
}
|
|
|
|
[$selected, $selectedCents] = $this->calibrate(
|
|
$groups,
|
|
$selected,
|
|
$targetCents,
|
|
);
|
|
|
|
$selectedByMaterial = [];
|
|
foreach ($groups as $materialNumber => $rows) {
|
|
foreach ($rows as $row) {
|
|
if (isset($selected[(int) $row['id']])) {
|
|
$selectedByMaterial[$materialNumber][] = $row;
|
|
}
|
|
}
|
|
}
|
|
|
|
$allocationRows = [];
|
|
foreach ($groups as $materialNumber => $rows) {
|
|
$selectedRows = $selectedByMaterial[$materialNumber] ?? [];
|
|
$allocationRows[] = [
|
|
'material_number' => (string) $materialNumber,
|
|
'total_cents' => array_sum(array_column($rows, 'amount_cents')),
|
|
'allocated_cents' => $allocations[$materialNumber],
|
|
'selected_cents' => array_sum(array_column($selectedRows, 'amount_cents')),
|
|
'selected_rows' => count($selectedRows),
|
|
'row_count' => count($rows),
|
|
];
|
|
}
|
|
usort(
|
|
$allocationRows,
|
|
static fn (array $left, array $right): int => strnatcasecmp(
|
|
$left['material_number'],
|
|
$right['material_number'],
|
|
),
|
|
);
|
|
|
|
$selectedIds = array_keys($selected);
|
|
sort($selectedIds, SORT_NUMERIC);
|
|
$differenceCents = $targetCents - $selectedCents;
|
|
|
|
return [
|
|
'exact' => $differenceCents === 0,
|
|
'target_cents' => $targetCents,
|
|
'total_cents' => $totalCents,
|
|
'selected_cents' => $selectedCents,
|
|
'difference_cents' => $differenceCents,
|
|
'selected_ids' => $selectedIds,
|
|
'selected_rows' => count($selectedIds),
|
|
'selected_materials' => count($selectedByMaterial),
|
|
'allocations' => $allocationRows,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
|
|
* @return array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>>
|
|
*/
|
|
private function normalizeGroups(array $groups): array
|
|
{
|
|
$normalized = [];
|
|
foreach ($groups as $materialNumber => $rows) {
|
|
$materialNumber = trim((string) $materialNumber);
|
|
if ($materialNumber === '') {
|
|
continue;
|
|
}
|
|
|
|
$validRows = array_values(array_filter(
|
|
$rows,
|
|
static fn (array $row): bool => (int) ($row['amount_cents'] ?? 0) > 0
|
|
&& (int) ($row['id'] ?? 0) > 0,
|
|
));
|
|
if ($validRows === []) {
|
|
continue;
|
|
}
|
|
usort($validRows, static function (array $left, array $right): int {
|
|
$dateComparison = strcmp((string) $left['date'], (string) $right['date']);
|
|
|
|
return $dateComparison !== 0
|
|
? $dateComparison
|
|
: ((int) $left['source_row_number'] <=> (int) $right['source_row_number']);
|
|
});
|
|
$normalized[$materialNumber] = $validRows;
|
|
}
|
|
ksort($normalized, SORT_NATURAL | SORT_FLAG_CASE);
|
|
|
|
return $normalized;
|
|
}
|
|
|
|
/**
|
|
* 先保证每个料号选中最早一行,再按剩余发货金额占比分配剩余过账金额。
|
|
*
|
|
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
|
|
* @return array<string,int>
|
|
*/
|
|
private function proportionalAllocations(
|
|
array $groups,
|
|
int $targetCents,
|
|
int $minimumCents,
|
|
): array {
|
|
if ($targetCents < $minimumCents) {
|
|
throw new InvalidArgumentException(sprintf(
|
|
'整月过账金额不足:每个料号至少选择一行需要 %s。',
|
|
number_format($minimumCents / 100, 2, '.', ','),
|
|
));
|
|
}
|
|
|
|
$extraTotal = 0;
|
|
$extraByMaterial = [];
|
|
$baseByMaterial = [];
|
|
foreach ($groups as $materialNumber => $rows) {
|
|
$base = (int) $rows[0]['amount_cents'];
|
|
$total = array_sum(array_column($rows, 'amount_cents'));
|
|
$baseByMaterial[$materialNumber] = $base;
|
|
$extraByMaterial[$materialNumber] = $total - $base;
|
|
$extraTotal += $total - $base;
|
|
}
|
|
|
|
$remaining = $targetCents - $minimumCents;
|
|
$allocations = [];
|
|
$remainders = [];
|
|
$assigned = 0;
|
|
foreach ($groups as $materialNumber => $rows) {
|
|
$extra = $extraByMaterial[$materialNumber];
|
|
$share = 0;
|
|
$remainder = '0';
|
|
if ($remaining > 0 && $extraTotal > 0 && $extra > 0) {
|
|
$numerator = bcmul((string) $extra, (string) $remaining, 0);
|
|
$share = (int) bcdiv($numerator, (string) $extraTotal, 0);
|
|
$remainder = bcmod($numerator, (string) $extraTotal);
|
|
}
|
|
$allocations[$materialNumber] = $baseByMaterial[$materialNumber] + $share;
|
|
$assigned += $share;
|
|
$remainders[$materialNumber] = $remainder;
|
|
}
|
|
|
|
$left = $remaining - $assigned;
|
|
if ($left > 0) {
|
|
$ordered = array_keys($groups);
|
|
usort($ordered, static function (string $leftMaterial, string $rightMaterial) use (
|
|
$remainders,
|
|
$extraByMaterial,
|
|
): int {
|
|
if ($extraByMaterial[$leftMaterial] <= 0) {
|
|
return 1;
|
|
}
|
|
if ($extraByMaterial[$rightMaterial] <= 0) {
|
|
return -1;
|
|
}
|
|
|
|
return bccomp($remainders[$rightMaterial], $remainders[$leftMaterial], 0)
|
|
?: strnatcasecmp($leftMaterial, $rightMaterial);
|
|
});
|
|
foreach ($ordered as $materialNumber) {
|
|
if ($left <= 0) {
|
|
break;
|
|
}
|
|
if ($extraByMaterial[$materialNumber] > $allocations[$materialNumber]
|
|
- $baseByMaterial[$materialNumber]) {
|
|
$allocations[$materialNumber]++;
|
|
$left--;
|
|
}
|
|
}
|
|
}
|
|
|
|
return $allocations;
|
|
}
|
|
|
|
/**
|
|
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
|
|
* @param array<int,true> $selected
|
|
* @return array{0:array<int,true>,1:int}
|
|
*/
|
|
private function calibrate(array $groups, array $selected, int $targetCents): array
|
|
{
|
|
$rowsById = [];
|
|
foreach ($groups as $materialNumber => $rows) {
|
|
foreach ($rows as $row) {
|
|
$id = (int) $row['id'];
|
|
$row['material_number'] = $materialNumber;
|
|
$rowsById[$id] = $row;
|
|
}
|
|
}
|
|
|
|
for ($attempt = 0; $attempt < count($groups) + 2; $attempt++) {
|
|
$selectedCents = 0;
|
|
foreach ($rowsById as $id => $row) {
|
|
if (isset($selected[$id])) {
|
|
$selectedCents += (int) $row['amount_cents'];
|
|
}
|
|
}
|
|
|
|
$difference = $targetCents - $selectedCents;
|
|
if ($difference === 0) {
|
|
return [$selected, $selectedCents];
|
|
}
|
|
|
|
$options = $this->prefixOptions($groups, $selected);
|
|
$adjustments = $this->exactPrefixAdjustment($options, $difference);
|
|
if ($adjustments === null) {
|
|
$adjustment = $this->bestApproximatePrefixOption($options, $difference);
|
|
if ($adjustment === null) {
|
|
return [$selected, $selectedCents];
|
|
}
|
|
if (abs($difference - $adjustment['delta']) >= abs($difference)) {
|
|
return [$selected, $selectedCents];
|
|
}
|
|
$adjustments = [$adjustment];
|
|
}
|
|
|
|
foreach ($adjustments as $adjustment) {
|
|
$materialNumber = $adjustment['material_number'];
|
|
foreach ($groups[$materialNumber] as $row) {
|
|
unset($selected[(int) $row['id']]);
|
|
}
|
|
for ($index = 0; $index < $adjustment['count']; $index++) {
|
|
$selected[(int) $groups[$materialNumber][$index]['id']] = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
$selectedCents = 0;
|
|
foreach (array_keys($selected) as $id) {
|
|
$selectedCents += (int) $rowsById[$id]['amount_cents'];
|
|
}
|
|
|
|
return [$selected, $selectedCents];
|
|
}
|
|
|
|
/**
|
|
* @param array<string,list<array<string,mixed>>> $groups
|
|
* @param array<int,true> $selected
|
|
* @return list<array{
|
|
* material_number:string,
|
|
* count:int,
|
|
* delta:int,
|
|
* count_change:int
|
|
* }>
|
|
*/
|
|
private function prefixOptions(
|
|
array $groups,
|
|
array $selected,
|
|
): array {
|
|
$options = [];
|
|
foreach ($groups as $materialNumber => $rows) {
|
|
$currentCents = 0;
|
|
$currentCount = 0;
|
|
foreach ($rows as $row) {
|
|
if (isset($selected[(int) $row['id']])) {
|
|
$currentCents += (int) $row['amount_cents'];
|
|
$currentCount++;
|
|
}
|
|
}
|
|
|
|
$prefixCents = 0;
|
|
foreach ($rows as $index => $row) {
|
|
$prefixCents += (int) $row['amount_cents'];
|
|
$count = $index + 1;
|
|
$delta = $prefixCents - $currentCents;
|
|
if ($delta !== 0) {
|
|
$options[] = [
|
|
'material_number' => (string) $materialNumber,
|
|
'count' => $count,
|
|
'delta' => $delta,
|
|
'count_change' => abs($count - $currentCount),
|
|
];
|
|
}
|
|
}
|
|
}
|
|
|
|
return $options;
|
|
}
|
|
|
|
/**
|
|
* 调整一个或两个料号的日期前缀,寻找精确差额。
|
|
*
|
|
* @param list<array{
|
|
* material_number:string,
|
|
* count:int,
|
|
* delta:int,
|
|
* count_change:int
|
|
* }> $options
|
|
* @return list<array{material_number:string,count:int,delta:int,count_change:int}>|null
|
|
*/
|
|
private function exactPrefixAdjustment(array $options, int $difference): ?array
|
|
{
|
|
$single = null;
|
|
foreach ($options as $option) {
|
|
if ($option['delta'] === $difference
|
|
&& ($single === null || $option['count_change'] < $single['count_change'])) {
|
|
$single = $option;
|
|
}
|
|
}
|
|
if ($single !== null) {
|
|
return [$single];
|
|
}
|
|
|
|
$byDelta = [];
|
|
foreach ($options as $option) {
|
|
$byDelta[$option['delta']][] = $option;
|
|
}
|
|
foreach ($options as $left) {
|
|
$needed = $difference - $left['delta'];
|
|
foreach ($byDelta[$needed] ?? [] as $right) {
|
|
if ($left['material_number'] === $right['material_number']) {
|
|
continue;
|
|
}
|
|
|
|
return [
|
|
$left,
|
|
$right,
|
|
];
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* @param list<array{
|
|
* material_number:string,
|
|
* count:int,
|
|
* delta:int,
|
|
* count_change:int
|
|
* }> $options
|
|
* @return array{material_number:string,count:int,delta:int,count_change:int}|null
|
|
*/
|
|
private function bestApproximatePrefixOption(
|
|
array $options,
|
|
int $difference,
|
|
): ?array {
|
|
$best = null;
|
|
$bestRemaining = abs($difference);
|
|
foreach ($options as $option) {
|
|
$remaining = abs($difference - $option['delta']);
|
|
if ($remaining < $bestRemaining
|
|
|| ($remaining === $bestRemaining
|
|
&& $best !== null
|
|
&& $option['count_change'] < $best['count_change'])) {
|
|
$best = $option;
|
|
$bestRemaining = $remaining;
|
|
}
|
|
}
|
|
|
|
return $best;
|
|
}
|
|
}
|