parent
2a3787f400
commit
bddfffecec
383
app/Business/KukaPostingBase/KukaPostingAmountPoster.php
Normal file
383
app/Business/KukaPostingBase/KukaPostingAmountPoster.php
Normal file
@ -0,0 +1,383 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\KukaPostingBase;
|
||||
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class KukaPostingAmountPoster
|
||||
{
|
||||
public const POSTING_LABEL = '过账标签';
|
||||
|
||||
public const POSTED_LABEL = '是';
|
||||
|
||||
public const SUPPLEMENT_LABEL = '补单(订单四组)';
|
||||
|
||||
private const UPDATE_CHUNK = 500;
|
||||
|
||||
public function __construct(
|
||||
private readonly DatabaseManager $databases,
|
||||
private readonly KukaPostingBaseRepository $repository,
|
||||
private readonly KukaPostingAmountSelection $selection,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function plan(int $companyId, string $period, string $targetAmount): array
|
||||
{
|
||||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
|
||||
throw new InvalidArgumentException('账期格式必须为 YYYY-MM。');
|
||||
}
|
||||
$targetCents = $this->amountToCents($targetAmount);
|
||||
if ($targetCents <= 0) {
|
||||
throw new InvalidArgumentException('整月过账金额必须大于 0。');
|
||||
}
|
||||
|
||||
$import = $this->repository->importFor($companyId, $period);
|
||||
if ($import === null) {
|
||||
throw new RuntimeException('当前账期尚未导入发货明细。');
|
||||
}
|
||||
|
||||
$connection = $this->connection();
|
||||
$sourceRows = [];
|
||||
$itemNumbers = [];
|
||||
$storedMaterialNumbers = [];
|
||||
$connection->table('kuka_posting_base_rows')
|
||||
->where('company_id', $companyId)
|
||||
->where('period', $period)
|
||||
->select([
|
||||
'id',
|
||||
'send_date',
|
||||
'order_date',
|
||||
'source_row_number',
|
||||
'source_values',
|
||||
])
|
||||
->orderBy('id')
|
||||
->chunkById(1000, function ($rows) use (
|
||||
&$sourceRows,
|
||||
&$itemNumbers,
|
||||
&$storedMaterialNumbers,
|
||||
): void {
|
||||
foreach ($rows as $row) {
|
||||
try {
|
||||
$values = json_decode(
|
||||
(string) $row->source_values,
|
||||
true,
|
||||
512,
|
||||
JSON_THROW_ON_ERROR,
|
||||
);
|
||||
} catch (Throwable) {
|
||||
$values = [];
|
||||
}
|
||||
if (! is_array($values)) {
|
||||
$values = [];
|
||||
}
|
||||
|
||||
$itemNumber = trim((string) ($values['货号'] ?? ''));
|
||||
if ($itemNumber !== '') {
|
||||
$itemNumbers[$itemNumber] = true;
|
||||
}
|
||||
$storedMaterialNumber = trim((string) ($values['物料编号'] ?? ''));
|
||||
$usesRepairedMaterial = trim((string) (
|
||||
$values['物料信息修正'] ?? ''
|
||||
)) === '是';
|
||||
if ($usesRepairedMaterial && $storedMaterialNumber !== '') {
|
||||
$storedMaterialNumbers[$storedMaterialNumber] = true;
|
||||
}
|
||||
$sourceRows[] = [
|
||||
'id' => (int) $row->id,
|
||||
'item_number' => $itemNumber,
|
||||
'stored_material_number' => $storedMaterialNumber,
|
||||
'uses_repaired_material' => $usesRepairedMaterial,
|
||||
'quantity' => $this->decimalString($values['实发数量'] ?? null),
|
||||
'date' => (string) ($row->send_date ?? $row->order_date ?? ''),
|
||||
'source_row_number' => (int) $row->source_row_number,
|
||||
];
|
||||
}
|
||||
});
|
||||
|
||||
if ($sourceRows === []) {
|
||||
throw new RuntimeException('当前账期没有发货明细行。');
|
||||
}
|
||||
|
||||
$maps = $this->repository->materialMaps($companyId, array_keys($itemNumbers));
|
||||
$quotations = $this->repository->effectiveQuotations(
|
||||
$companyId,
|
||||
collect($maps)
|
||||
->pluck('material_number')
|
||||
->filter()
|
||||
->merge(array_keys($storedMaterialNumbers))
|
||||
->unique()
|
||||
->values()
|
||||
->all(),
|
||||
);
|
||||
|
||||
$groups = [];
|
||||
$eligibleRows = 0;
|
||||
foreach ($sourceRows as $row) {
|
||||
$materialNumber = trim((string) ($row['stored_material_number'] ?? ''));
|
||||
if (! $row['uses_repaired_material'] || $materialNumber === '') {
|
||||
$materialNumber = trim((string) (
|
||||
$maps[$row['item_number']]->material_number ?? ''
|
||||
));
|
||||
}
|
||||
$quotation = $materialNumber === '' ? null : ($quotations[$materialNumber] ?? null);
|
||||
if ($materialNumber === '' || $quotation === null || $row['quantity'] === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$amount = bcmul(
|
||||
$this->decimalString($quotation->price_including_tax) ?? '0',
|
||||
$row['quantity'],
|
||||
4,
|
||||
);
|
||||
$amountCents = $this->amountToCents($amount);
|
||||
if ($amountCents <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$groups[$materialNumber][] = [
|
||||
'id' => (int) $row['id'],
|
||||
'amount_cents' => $amountCents,
|
||||
'date' => (string) $row['date'],
|
||||
'source_row_number' => (int) $row['source_row_number'],
|
||||
];
|
||||
$eligibleRows++;
|
||||
}
|
||||
|
||||
$result = $this->selection->select($groups, $targetCents);
|
||||
$fingerprint = hash('sha256', json_encode([
|
||||
'company_id' => $companyId,
|
||||
'period' => $period,
|
||||
'target_cents' => $targetCents,
|
||||
'file_sha256' => (string) $import->file_sha256,
|
||||
'selected_ids' => $result['selected_ids'],
|
||||
'selected_cents' => $result['selected_cents'],
|
||||
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
|
||||
return [
|
||||
'company_id' => $companyId,
|
||||
'period' => $period,
|
||||
'target_cents' => $result['target_cents'],
|
||||
'target_amount' => $this->formatAmount($result['target_cents']),
|
||||
'total_cents' => $result['total_cents'],
|
||||
'total_amount' => $this->formatAmount($result['total_cents']),
|
||||
'selected_cents' => $result['selected_cents'],
|
||||
'selected_amount' => $this->formatAmount($result['selected_cents']),
|
||||
'difference_cents' => $result['difference_cents'],
|
||||
'difference_amount' => $this->formatAmount(abs($result['difference_cents'])),
|
||||
'is_exact' => (bool) $result['exact'],
|
||||
'rows_total' => count($sourceRows),
|
||||
'eligible_rows' => $eligibleRows,
|
||||
'uncalculable_rows' => count($sourceRows) - $eligibleRows,
|
||||
'selected_rows' => (int) $result['selected_rows'],
|
||||
'material_count' => count($groups),
|
||||
'selected_material_count' => (int) $result['selected_materials'],
|
||||
'selected_ids' => $result['selected_ids'],
|
||||
'allocations' => $result['allocations'],
|
||||
'preview_hash' => $fingerprint,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $plan
|
||||
* @return array{updated:int,unchanged:int}
|
||||
*/
|
||||
public function apply(array $plan, ?int $userId = null): array
|
||||
{
|
||||
if (($plan['is_exact'] ?? false) !== true) {
|
||||
throw new InvalidArgumentException('过账金额与选中发货金额仍有差额,未写入过账标签。');
|
||||
}
|
||||
|
||||
$companyId = (int) ($plan['company_id'] ?? 0);
|
||||
$period = (string) ($plan['period'] ?? '');
|
||||
$selectedIds = array_fill_keys(array_map('intval', (array) ($plan['selected_ids'] ?? [])), true);
|
||||
$connection = $this->connection();
|
||||
$now = now();
|
||||
$updated = 0;
|
||||
$unchanged = 0;
|
||||
|
||||
$connection->transaction(function () use (
|
||||
$connection,
|
||||
$companyId,
|
||||
$period,
|
||||
$selectedIds,
|
||||
$now,
|
||||
$userId,
|
||||
$plan,
|
||||
&$updated,
|
||||
&$unchanged,
|
||||
): void {
|
||||
$batch = [];
|
||||
$flush = static function () use ($connection, &$batch): void {
|
||||
if ($batch === []) {
|
||||
return;
|
||||
}
|
||||
$connection->table('kuka_posting_base_rows')->upsert(
|
||||
$batch,
|
||||
['company_id', 'period', 'source_row_number'],
|
||||
[
|
||||
'store_name',
|
||||
'internal_order_no',
|
||||
'online_order_no',
|
||||
'product_code',
|
||||
'source_values',
|
||||
'row_hash',
|
||||
'imported_at',
|
||||
],
|
||||
);
|
||||
$batch = [];
|
||||
};
|
||||
|
||||
$connection->table('kuka_posting_base_rows')
|
||||
->where('company_id', $companyId)
|
||||
->where('period', $period)
|
||||
->orderBy('id')
|
||||
->chunkById(self::UPDATE_CHUNK, function ($rows) use (
|
||||
$selectedIds,
|
||||
&$updated,
|
||||
&$unchanged,
|
||||
&$batch,
|
||||
$flush,
|
||||
): void {
|
||||
foreach ($rows as $row) {
|
||||
try {
|
||||
$values = json_decode(
|
||||
(string) $row->source_values,
|
||||
true,
|
||||
512,
|
||||
JSON_THROW_ON_ERROR,
|
||||
);
|
||||
} catch (Throwable) {
|
||||
$values = [];
|
||||
}
|
||||
if (! is_array($values)) {
|
||||
$values = [];
|
||||
}
|
||||
$label = isset($selectedIds[(int) $row->id])
|
||||
? self::POSTED_LABEL
|
||||
: self::SUPPLEMENT_LABEL;
|
||||
if (trim((string) ($values[self::POSTING_LABEL] ?? '')) === $label) {
|
||||
$unchanged++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$values[self::POSTING_LABEL] = $label;
|
||||
$encoded = json_encode(
|
||||
$values,
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
|
||||
);
|
||||
$batch[] = [
|
||||
'company_id' => (int) $row->company_id,
|
||||
'period' => (string) $row->period,
|
||||
'source_row_number' => (int) $row->source_row_number,
|
||||
'store_name' => (string) $row->store_name,
|
||||
'internal_order_no' => $row->internal_order_no,
|
||||
'online_order_no' => $row->online_order_no,
|
||||
'product_code' => $row->product_code,
|
||||
'source_values' => $encoded,
|
||||
'row_hash' => hash('sha256', $encoded),
|
||||
'imported_at' => $row->imported_at,
|
||||
];
|
||||
$updated++;
|
||||
if (count($batch) >= self::UPDATE_CHUNK) {
|
||||
$flush();
|
||||
}
|
||||
}
|
||||
});
|
||||
$flush();
|
||||
|
||||
$connection->table('kuka_posting_base_imports')
|
||||
->where('company_id', $companyId)
|
||||
->where('period', $period)
|
||||
->update([
|
||||
'posting_target_amount' => $plan['target_amount'],
|
||||
'posting_selected_amount' => $plan['selected_amount'],
|
||||
'posting_difference_amount' => '0.00',
|
||||
'posting_selected_rows' => (int) $plan['selected_rows'],
|
||||
'posting_material_count' => (int) $plan['material_count'],
|
||||
'posting_uncalculable_rows' => (int) $plan['uncalculable_rows'],
|
||||
'posting_allocation_json' => json_encode(
|
||||
$plan['allocations'],
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
|
||||
),
|
||||
'posting_snapshot_hash' => (string) $plan['preview_hash'],
|
||||
'posting_applied_by' => $userId,
|
||||
'posting_applied_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
});
|
||||
|
||||
return ['updated' => $updated, 'unchanged' => $unchanged];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $plan
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function previewSummary(array $plan): array
|
||||
{
|
||||
return [
|
||||
'period' => (string) $plan['period'],
|
||||
'target_cents' => (int) $plan['target_cents'],
|
||||
'target_amount' => (string) $plan['target_amount'],
|
||||
'total_cents' => (int) $plan['total_cents'],
|
||||
'total_amount' => (string) $plan['total_amount'],
|
||||
'selected_cents' => (int) $plan['selected_cents'],
|
||||
'selected_amount' => (string) $plan['selected_amount'],
|
||||
'difference_cents' => (int) $plan['difference_cents'],
|
||||
'difference_amount' => (string) $plan['difference_amount'],
|
||||
'is_exact' => (bool) $plan['is_exact'],
|
||||
'rows_total' => (int) $plan['rows_total'],
|
||||
'uncalculable_rows' => (int) $plan['uncalculable_rows'],
|
||||
'selected_rows' => (int) $plan['selected_rows'],
|
||||
'material_count' => (int) $plan['material_count'],
|
||||
'selected_material_count' => (int) $plan['selected_material_count'],
|
||||
'preview_hash' => (string) $plan['preview_hash'],
|
||||
];
|
||||
}
|
||||
|
||||
private function decimalString(mixed $value): ?string
|
||||
{
|
||||
$normalized = str_replace(',', '', trim((string) $value));
|
||||
if ($normalized === '' || ! is_numeric($normalized)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
private function amountToCents(string $amount): int
|
||||
{
|
||||
$normalized = str_replace([',', ' '], '', trim($amount));
|
||||
if (preg_match('/^(\d+)(?:\.(\d+))?$/', $normalized, $matches) !== 1) {
|
||||
throw new InvalidArgumentException('金额格式不正确。');
|
||||
}
|
||||
|
||||
$whole = (int) $matches[1];
|
||||
$fraction = str_pad($matches[2] ?? '', 3, '0');
|
||||
$cents = ($whole * 100) + (int) substr($fraction, 0, 2);
|
||||
if ((int) $fraction[2] >= 5) {
|
||||
$cents++;
|
||||
}
|
||||
|
||||
return $cents;
|
||||
}
|
||||
|
||||
private function formatAmount(int $cents): string
|
||||
{
|
||||
return bcdiv((string) $cents, '100', 2);
|
||||
}
|
||||
|
||||
private function connection(): ConnectionInterface
|
||||
{
|
||||
return $this->databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
}
|
||||
}
|
||||
418
app/Business/KukaPostingBase/KukaPostingAmountSelection.php
Normal file
418
app/Business/KukaPostingBase/KukaPostingAmountSelection.php
Normal file
@ -0,0 +1,418 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@ -21,6 +21,7 @@ class KukaPostingBasePageData
|
||||
* statuses: list<string>,
|
||||
* stores: list<string>,
|
||||
* import: ?array<string, mixed>,
|
||||
* posting_amount: ?array<string, mixed>,
|
||||
* summary: array<string, mixed>,
|
||||
* error: ?string
|
||||
* }
|
||||
@ -182,6 +183,7 @@ class KukaPostingBasePageData
|
||||
|
||||
$import = $available ? $this->repository->importFor($companyId, $period) : null;
|
||||
$importData = null;
|
||||
$postingAmount = null;
|
||||
if ($import !== null) {
|
||||
$storeCounts = json_decode((string) ($import->store_counts ?? ''), true);
|
||||
$importData = [
|
||||
@ -195,6 +197,20 @@ class KukaPostingBasePageData
|
||||
'source_sheet' => (string) $import->source_sheet,
|
||||
'completed_at' => (string) $import->completed_at,
|
||||
];
|
||||
if (property_exists($import, 'posting_target_amount')
|
||||
&& $import->posting_target_amount !== null) {
|
||||
$postingAmount = [
|
||||
'target_amount' => bcdiv((string) $import->posting_target_amount, '1', 2),
|
||||
'selected_amount' => bcdiv((string) $import->posting_selected_amount, '1', 2),
|
||||
'difference_amount' => bcdiv((string) $import->posting_difference_amount, '1', 2),
|
||||
'selected_rows' => (int) $import->posting_selected_rows,
|
||||
'material_count' => (int) $import->posting_material_count,
|
||||
'uncalculable_rows' => (int) $import->posting_uncalculable_rows,
|
||||
'applied_at' => $import->posting_applied_at
|
||||
? (string) $import->posting_applied_at
|
||||
: null,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
@ -211,6 +227,7 @@ class KukaPostingBasePageData
|
||||
'statuses' => $statuses,
|
||||
'stores' => $stores,
|
||||
'import' => $importData,
|
||||
'posting_amount' => $postingAmount,
|
||||
'summary' => [
|
||||
'filtered_rows' => $rows->total(),
|
||||
'rows' => (int) ($importData['row_count'] ?? 0),
|
||||
|
||||
128
app/Http/Controllers/Business/KukaPostingAmountPosting.php
Normal file
128
app/Http/Controllers/Business/KukaPostingAmountPosting.php
Normal file
@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use App\Business\KukaPostingBase\KukaPostingAmountPoster;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class KukaPostingAmountPosting extends Controller
|
||||
{
|
||||
public function preview(
|
||||
Request $request,
|
||||
KukaPostingAmountPoster $poster,
|
||||
): RedirectResponse {
|
||||
$data = $this->validatePlan($request);
|
||||
$companyId = (int) (company_id() ?: 1);
|
||||
|
||||
try {
|
||||
$plan = $poster->plan($companyId, $data['period'], $data['target_amount']);
|
||||
} catch (InvalidArgumentException | RuntimeException $exception) {
|
||||
return $this->redirectToPage($request, $data['period'])
|
||||
->withInput()
|
||||
->withErrors(['posting_amount' => $exception->getMessage()]);
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return $this->redirectToPage($request, $data['period'])
|
||||
->withInput()
|
||||
->withErrors(['posting_amount' => '过账金额暂时无法计算,请稍后重试。']);
|
||||
}
|
||||
|
||||
return $this->redirectToPage($request, $data['period'])
|
||||
->withInput()
|
||||
->with('kuka_posting_amount_preview', $poster->previewSummary($plan));
|
||||
}
|
||||
|
||||
public function apply(
|
||||
Request $request,
|
||||
KukaPostingAmountPoster $poster,
|
||||
): RedirectResponse {
|
||||
$data = $request->validate([
|
||||
'period' => ['required', 'string', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'],
|
||||
'target_amount' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/', 'not_in:0,0.0,0.00'],
|
||||
'preview_hash' => ['required', 'string', 'size:64'],
|
||||
], $this->messages());
|
||||
$companyId = (int) (company_id() ?: 1);
|
||||
|
||||
try {
|
||||
$plan = $poster->plan($companyId, $data['period'], $data['target_amount']);
|
||||
if (! hash_equals((string) $plan['preview_hash'], (string) $data['preview_hash'])) {
|
||||
throw new InvalidArgumentException('发货明细或物料金额已经变化,请重新计算过账方案。');
|
||||
}
|
||||
if (($plan['is_exact'] ?? false) !== true) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'过账金额与选中发货金额仍有差额 %s,未写入过账标签。',
|
||||
number_format((int) $plan['difference_cents'] / 100, 2, '.', ','),
|
||||
));
|
||||
}
|
||||
|
||||
$result = $poster->apply($plan, auth()->id());
|
||||
} catch (InvalidArgumentException | RuntimeException $exception) {
|
||||
return $this->redirectToPage($request, $data['period'])
|
||||
->withInput()
|
||||
->withErrors(['posting_amount' => $exception->getMessage()]);
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return $this->redirectToPage($request, $data['period'])
|
||||
->withInput()
|
||||
->withErrors(['posting_amount' => '过账标签写入失败,原有标签已保留。']);
|
||||
}
|
||||
|
||||
return $this->redirectToPage($request, $data['period'])->with(
|
||||
'success',
|
||||
sprintf(
|
||||
'整月过账标签已更新:%s 行标记为“是”,其余标记为“补单(订单四组)”;本次变更 %s 行。',
|
||||
number_format((int) $plan['selected_rows']),
|
||||
number_format((int) $result['updated']),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{period:string,target_amount:string}
|
||||
*/
|
||||
private function validatePlan(Request $request): array
|
||||
{
|
||||
return $request->validate([
|
||||
'period' => ['required', 'string', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'],
|
||||
'target_amount' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/', 'not_in:0,0.0,0.00'],
|
||||
], $this->messages());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,string>
|
||||
*/
|
||||
private function messages(): array
|
||||
{
|
||||
return [
|
||||
'period.required' => '请选择需要过账的账期。',
|
||||
'period.regex' => '账期格式必须为 YYYY-MM。',
|
||||
'target_amount.required' => '请填写整月过账金额。',
|
||||
'target_amount.regex' => '整月过账金额最多保留两位小数。',
|
||||
'target_amount.not_in' => '整月过账金额必须大于 0。',
|
||||
'preview_hash.required' => '请先计算过账方案。',
|
||||
'preview_hash.size' => '过账方案已失效,请重新计算。',
|
||||
];
|
||||
}
|
||||
|
||||
private function redirectToPage(Request $request, string $period): RedirectResponse
|
||||
{
|
||||
return redirect()->route('business.pages.show', [
|
||||
'company_id' => company_id() ?: 1,
|
||||
'section' => 'posting-data',
|
||||
'page' => 'kuka-basic-data',
|
||||
'submenu' => 'shipments',
|
||||
'period' => $period,
|
||||
'store_name' => mb_substr(trim((string) $request->input('store_name', '')), 0, 191),
|
||||
'status' => mb_substr(trim((string) $request->input('status', '')), 0, 64),
|
||||
'keyword' => mb_substr(trim((string) $request->input('keyword', '')), 0, 120),
|
||||
'per_page' => max(1, min(200, (int) $request->input('per_page', 50))),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private function connection(): string
|
||||
{
|
||||
return (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
}
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
$schema = Schema::connection($this->connection());
|
||||
if (! $schema->hasTable('kuka_posting_base_imports')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$schema->table('kuka_posting_base_imports', function (Blueprint $table) use ($schema): void {
|
||||
if (! $schema->hasColumn('kuka_posting_base_imports', 'posting_target_amount')) {
|
||||
$table->decimal('posting_target_amount', 18, 2)->nullable();
|
||||
$table->decimal('posting_selected_amount', 18, 2)->nullable();
|
||||
$table->decimal('posting_difference_amount', 18, 2)->nullable();
|
||||
$table->unsignedInteger('posting_selected_rows')->nullable();
|
||||
$table->unsignedInteger('posting_material_count')->nullable();
|
||||
$table->unsignedInteger('posting_uncalculable_rows')->nullable();
|
||||
$table->longText('posting_allocation_json')->nullable();
|
||||
$table->char('posting_snapshot_hash', 64)->nullable();
|
||||
$table->unsignedBigInteger('posting_applied_by')->nullable();
|
||||
$table->timestamp('posting_applied_at')->nullable();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$schema = Schema::connection($this->connection());
|
||||
if (! $schema->hasTable('kuka_posting_base_imports')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$schema->table('kuka_posting_base_imports', function (Blueprint $table) use ($schema): void {
|
||||
$columns = [
|
||||
'posting_target_amount',
|
||||
'posting_selected_amount',
|
||||
'posting_difference_amount',
|
||||
'posting_selected_rows',
|
||||
'posting_material_count',
|
||||
'posting_uncalculable_rows',
|
||||
'posting_allocation_json',
|
||||
'posting_snapshot_hash',
|
||||
'posting_applied_by',
|
||||
'posting_applied_at',
|
||||
];
|
||||
$existing = array_values(array_filter(
|
||||
$columns,
|
||||
static fn (string $column): bool => $schema->hasColumn(
|
||||
'kuka_posting_base_imports',
|
||||
$column,
|
||||
),
|
||||
));
|
||||
if ($existing !== []) {
|
||||
$table->dropColumn($existing);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
@ -8,6 +8,13 @@
|
||||
$stores = $base['stores'] ?? [];
|
||||
$import = $base['import'] ?? null;
|
||||
$summary = $base['summary'] ?? [];
|
||||
$postingAmount = $base['posting_amount'] ?? null;
|
||||
$postingPreview = session('kuka_posting_amount_preview');
|
||||
$postingAmountError = $errors->first('posting_amount');
|
||||
$postingTargetValue = old(
|
||||
'target_amount',
|
||||
$postingPreview['target_amount'] ?? ($postingAmount['target_amount'] ?? ''),
|
||||
);
|
||||
$error = $base['error'] ?? null;
|
||||
$resetUrl = route('business.pages.show', ['section' => 'posting-data', 'page' => 'kuka-basic-data']);
|
||||
@endphp
|
||||
@ -158,6 +165,197 @@
|
||||
color: var(--kb-ink);
|
||||
}
|
||||
|
||||
.kuka-posting-amount {
|
||||
margin-bottom: 1rem;
|
||||
padding: 1rem;
|
||||
border: 1px solid var(--kb-border);
|
||||
border-radius: 0.75rem;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__title {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: flex-start;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__title .material-icons-outlined {
|
||||
flex: 0 0 auto;
|
||||
margin-top: 0.05rem;
|
||||
color: var(--kb-gold-dark);
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__title strong {
|
||||
display: block;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__title p {
|
||||
margin: 0.22rem 0 0;
|
||||
color: var(--kb-muted);
|
||||
font-size: 0.7rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__applied {
|
||||
flex: 0 0 auto;
|
||||
color: var(--kb-muted);
|
||||
font-size: 0.68rem;
|
||||
line-height: 1.5;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__form {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(15rem, 22rem) auto;
|
||||
align-items: end;
|
||||
gap: 0.65rem;
|
||||
margin-top: 0.9rem;
|
||||
padding-top: 0.85rem;
|
||||
border-top: 1px solid #ebe6dd;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__form label {
|
||||
display: grid;
|
||||
gap: 0.28rem;
|
||||
color: var(--kb-muted);
|
||||
font-size: 0.7rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__form input {
|
||||
width: 100%;
|
||||
height: 2.125rem;
|
||||
padding: 0 0.65rem;
|
||||
border: 1px solid var(--kb-border);
|
||||
border-radius: 0.5rem;
|
||||
background: #fff;
|
||||
color: var(--kb-ink);
|
||||
font: inherit;
|
||||
font-size: 0.8rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
outline: none;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__form input:focus {
|
||||
border-color: var(--kb-gold-dark);
|
||||
box-shadow: 0 0 0 3px rgba(133, 102, 50, 0.16);
|
||||
}
|
||||
|
||||
.kuka-posting-amount__form button,
|
||||
.kuka-posting-amount__apply button {
|
||||
display: inline-flex;
|
||||
height: 2.125rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 0.9rem;
|
||||
border: 1px solid var(--kb-gold-dark);
|
||||
border-radius: 0.5rem;
|
||||
background: var(--kb-gold-dark);
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-size: 0.75rem;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__error,
|
||||
.kuka-posting-amount__warning,
|
||||
.kuka-posting-amount__success {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.45rem;
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.65rem 0.75rem;
|
||||
border-radius: 0.5rem;
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__error {
|
||||
border: 1px solid #dfbbbb;
|
||||
background: #fff4f4;
|
||||
color: var(--vip-danger, #b80000);
|
||||
}
|
||||
|
||||
.kuka-posting-amount__warning {
|
||||
border: 1px solid #e1c999;
|
||||
background: #fff9ed;
|
||||
color: var(--vip-warning, #935f07);
|
||||
}
|
||||
|
||||
.kuka-posting-amount__success {
|
||||
border: 1px solid #c8d8be;
|
||||
background: #f5faf1;
|
||||
color: var(--vip-success, #53793e);
|
||||
}
|
||||
|
||||
.kuka-posting-amount__preview {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
gap: 0.55rem;
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__metric {
|
||||
min-width: 0;
|
||||
padding: 0.6rem 0.7rem;
|
||||
border: 1px solid #e8e1d5;
|
||||
border-radius: 0.5rem;
|
||||
background: #fffdf8;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__metric span {
|
||||
display: block;
|
||||
color: var(--kb-muted);
|
||||
font-size: 0.66rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__metric strong {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
margin-top: 0.18rem;
|
||||
font-size: 0.82rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1.4;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__apply {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-top: 0.75rem;
|
||||
padding-top: 0.75rem;
|
||||
border-top: 1px solid #ebe6dd;
|
||||
}
|
||||
|
||||
.kuka-posting-amount__apply p {
|
||||
margin: 0;
|
||||
color: var(--kb-muted);
|
||||
font-size: 0.7rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
@media (max-width: 980px) {
|
||||
.kuka-posting-amount__preview { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
.kuka-base-filter { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.kuka-base-filter__actions { grid-column: 1 / -1; }
|
||||
@ -166,6 +364,11 @@
|
||||
@media (max-width: 760px) {
|
||||
.kuka-base-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.kuka-base-filter { grid-template-columns: 1fr; }
|
||||
.kuka-posting-amount__head,
|
||||
.kuka-posting-amount__apply { flex-direction: column; align-items: stretch; }
|
||||
.kuka-posting-amount__applied { text-align: left; }
|
||||
.kuka-posting-amount__form { grid-template-columns: 1fr; }
|
||||
.kuka-posting-amount__preview { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
</style>
|
||||
|
||||
@ -177,6 +380,106 @@
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<section class="kuka-posting-amount" data-kuka-posting-amount-panel aria-label="整月过账金额">
|
||||
<div class="kuka-posting-amount__head">
|
||||
<div class="kuka-posting-amount__title">
|
||||
<span class="material-icons-outlined" aria-hidden="true">account_balance_wallet</span>
|
||||
<div>
|
||||
<strong>整月过账金额</strong>
|
||||
<p>按每个料号本月发货金额占比分配,同料号按发货日期优先选择;只有“是”明细合计与整月金额完全一致时才允许写入标签。</p>
|
||||
</div>
|
||||
</div>
|
||||
@if ($postingAmount)
|
||||
<div class="kuka-posting-amount__applied">
|
||||
<div>上次过账 {{ number_format((float) $postingAmount['target_amount'], 2) }}</div>
|
||||
<div>{{ $postingAmount['applied_at'] ? \Illuminate\Support\Carbon::parse($postingAmount['applied_at'])->format('Y-m-d H:i') : '时间未记录' }}</div>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<form class="kuka-posting-amount__form" method="POST" action="{{ route('business.kuka-posting-amount.preview') }}">
|
||||
@csrf
|
||||
<input type="hidden" name="period" value="{{ $filters['period'] ?? '' }}">
|
||||
<input type="hidden" name="store_name" value="{{ $filters['store_name'] ?? '' }}">
|
||||
<input type="hidden" name="status" value="{{ $filters['status'] ?? '' }}">
|
||||
<input type="hidden" name="keyword" value="{{ $filters['keyword'] ?? '' }}">
|
||||
<input type="hidden" name="per_page" value="{{ (int) ($filters['per_page'] ?? 50) }}">
|
||||
<label>
|
||||
填写整月总过账金额
|
||||
<input
|
||||
type="text"
|
||||
name="target_amount"
|
||||
value="{{ $postingTargetValue }}"
|
||||
inputmode="decimal"
|
||||
autocomplete="off"
|
||||
placeholder="例如 1661276.90"
|
||||
aria-label="整月总过账金额"
|
||||
>
|
||||
</label>
|
||||
<button type="submit">计算分配方案</button>
|
||||
</form>
|
||||
|
||||
@if ($postingAmountError)
|
||||
<div class="kuka-posting-amount__error" role="alert">
|
||||
<span class="material-icons-outlined" aria-hidden="true">error_outline</span>
|
||||
<span>{{ $postingAmountError }}</span>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if (is_array($postingPreview))
|
||||
@php
|
||||
$previewExact = (bool) ($postingPreview['is_exact'] ?? false);
|
||||
$previewDifference = (int) ($postingPreview['difference_cents'] ?? 0);
|
||||
@endphp
|
||||
<div class="{{ $previewExact ? 'kuka-posting-amount__success' : 'kuka-posting-amount__warning' }}" role="status">
|
||||
<span class="material-icons-outlined" aria-hidden="true">{{ $previewExact ? 'verified' : 'warning_amber' }}</span>
|
||||
<span>
|
||||
@if ($previewExact)
|
||||
方案已精确匹配到分,可以确认写入过账标签。
|
||||
@else
|
||||
当前方案与整月过账金额相差 {{ number_format(abs($previewDifference) / 100, 2) }},系统不会写入任何标签,请调整整月金额后重新计算。
|
||||
@endif
|
||||
</span>
|
||||
</div>
|
||||
<div class="kuka-posting-amount__preview" aria-label="过账分配预览">
|
||||
<div class="kuka-posting-amount__metric">
|
||||
<span>整月过账金额</span>
|
||||
<strong>{{ number_format((int) $postingPreview['target_cents'] / 100, 2) }}</strong>
|
||||
</div>
|
||||
<div class="kuka-posting-amount__metric">
|
||||
<span>选中发货金额</span>
|
||||
<strong>{{ number_format((int) $postingPreview['selected_cents'] / 100, 2) }}</strong>
|
||||
</div>
|
||||
<div class="kuka-posting-amount__metric">
|
||||
<span>差额</span>
|
||||
<strong>{{ number_format(abs((int) $postingPreview['difference_cents']) / 100, 2) }}</strong>
|
||||
</div>
|
||||
<div class="kuka-posting-amount__metric">
|
||||
<span>“是”行 / 料号</span>
|
||||
<strong>{{ number_format((int) $postingPreview['selected_rows']) }} / {{ number_format((int) $postingPreview['selected_material_count']) }}</strong>
|
||||
</div>
|
||||
<div class="kuka-posting-amount__metric">
|
||||
<span>无法计算金额行</span>
|
||||
<strong>{{ number_format((int) $postingPreview['uncalculable_rows']) }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
@if ($previewExact)
|
||||
<form class="kuka-posting-amount__apply" method="POST" action="{{ route('business.kuka-posting-amount.apply') }}">
|
||||
@csrf
|
||||
<input type="hidden" name="period" value="{{ $postingPreview['period'] }}">
|
||||
<input type="hidden" name="target_amount" value="{{ $postingPreview['target_amount'] }}">
|
||||
<input type="hidden" name="preview_hash" value="{{ $postingPreview['preview_hash'] }}">
|
||||
<input type="hidden" name="store_name" value="{{ $filters['store_name'] ?? '' }}">
|
||||
<input type="hidden" name="status" value="{{ $filters['status'] ?? '' }}">
|
||||
<input type="hidden" name="keyword" value="{{ $filters['keyword'] ?? '' }}">
|
||||
<input type="hidden" name="per_page" value="{{ (int) ($filters['per_page'] ?? 50) }}">
|
||||
<p>确认后,“是”明细进入顾家对账;其余明细统一标记为“补单(订单四组)”。</p>
|
||||
<button type="submit">确认写入过账标签</button>
|
||||
</form>
|
||||
@endif
|
||||
@endif
|
||||
</section>
|
||||
|
||||
<section class="kuka-base-summary" aria-label="基础数据汇总">
|
||||
<article class="kuka-base-card">
|
||||
<span>账期</span>
|
||||
|
||||
@ -12,6 +12,7 @@ use App\Http\Controllers\Business\CompanyPlan;
|
||||
use App\Http\Controllers\Business\CourierSurchargeQuotes;
|
||||
use App\Http\Controllers\Business\CourierSurchargeTypes;
|
||||
use App\Http\Controllers\Business\InternalFlowReportActions;
|
||||
use App\Http\Controllers\Business\KukaPostingAmountPosting;
|
||||
use App\Http\Controllers\Business\ProductPrices;
|
||||
use App\Http\Controllers\Business\ServiceCompanyReconciliation as ServiceCompanyReconciliationController;
|
||||
use App\Http\Controllers\Business\SupplierPayableActions;
|
||||
@ -908,6 +909,15 @@ Route::get('workspace/posting-data/kuka-reconciliation/posting-data/export', 'Bu
|
||||
->middleware('business.page:posting-data,kuka-reconciliation')
|
||||
->name('business.kuka-reconciliation.posting-data.export');
|
||||
|
||||
Route::prefix('workspace/posting-data/kuka-basic-data/posting-amount')
|
||||
->name('business.kuka-posting-amount.')
|
||||
->middleware('business.page:posting-data,kuka-basic-data')
|
||||
->group(function (): void {
|
||||
$controller = KukaPostingAmountPosting::class;
|
||||
Route::post('preview', [$controller, 'preview'])->name('preview');
|
||||
Route::post('apply', [$controller, 'apply'])->name('apply');
|
||||
});
|
||||
|
||||
Route::get('workspace/posting-data/kuka-reconciliation/lingshan-statement/print', 'Business\Pages@printKukaLingshanStatement')
|
||||
->middleware('business.page:posting-data,kuka-reconciliation')
|
||||
->name('business.kuka-reconciliation.lingshan-statement.print');
|
||||
|
||||
@ -531,6 +531,124 @@ class KukaPostingBasePageTest extends FeatureTestCase
|
||||
@unlink($incomplete);
|
||||
}
|
||||
|
||||
public function test_monthly_posting_amount_previews_and_updates_all_labels_transactionally(): void
|
||||
{
|
||||
$file = $this->workbook();
|
||||
$this->artisan('business-mirror:import-kuka-posting-base', [
|
||||
'path' => $file,
|
||||
'--month' => '2026-10',
|
||||
'--company' => (string) $this->company->id,
|
||||
])->assertExitCode(0);
|
||||
|
||||
$connection = DB::connection('business_mirror');
|
||||
$originalRows = $connection->table('kuka_posting_base_rows')
|
||||
->where('company_id', $this->company->id)
|
||||
->where('period', '2026-10')
|
||||
->orderBy('source_row_number')
|
||||
->get();
|
||||
$this->assertCount(12, $originalRows);
|
||||
|
||||
$now = now();
|
||||
foreach ($originalRows as $index => $row) {
|
||||
$values = json_decode((string) $row->source_values, true, 512, JSON_THROW_ON_ERROR);
|
||||
$materialNumber = sprintf('91.FLOW.%02d', $index);
|
||||
$connection->table('kuka_posting_material_map_rows')->insert([
|
||||
'company_id' => $this->company->id,
|
||||
'item_number' => $values['货号'],
|
||||
'material_number' => $materialNumber,
|
||||
'match_status' => 'matched',
|
||||
'match_source' => 'barcode_material_no',
|
||||
'candidate_count' => 1,
|
||||
'candidate_materials' => json_encode([$materialNumber], JSON_THROW_ON_ERROR),
|
||||
'synced_at' => $now,
|
||||
]);
|
||||
$connection->table('kuka_posting_quotation_rows')->insert([
|
||||
'company_id' => $this->company->id,
|
||||
'material_number' => $materialNumber,
|
||||
'material_desc' => '过账分配测试物料',
|
||||
'record_status' => '生效',
|
||||
'price_including_tax' => '100.0000',
|
||||
'price_excluding_tax' => '88.5000',
|
||||
'row_hash' => hash('sha256', 'quote-' . $materialNumber),
|
||||
'source_values' => '{}',
|
||||
'source_row_number' => $index + 100,
|
||||
'imported_at' => $now,
|
||||
]);
|
||||
|
||||
$values['发货日期'] = '2026-10-20 11:00:00';
|
||||
$encoded = json_encode(
|
||||
$values,
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
|
||||
);
|
||||
$duplicate = (array) $row;
|
||||
unset($duplicate['id']);
|
||||
$duplicate['send_date'] = '2026-10-20 11:00:00';
|
||||
$duplicate['source_values'] = $encoded;
|
||||
$duplicate['row_hash'] = hash('sha256', $encoded);
|
||||
$duplicate['source_row_number'] = (int) $row->source_row_number + 100;
|
||||
$connection->table('kuka_posting_base_rows')->insert($duplicate);
|
||||
}
|
||||
|
||||
$this->loginAs();
|
||||
$previewResponse = $this->post(route('business.kuka-posting-amount.preview'), [
|
||||
'period' => '2026-10',
|
||||
'target_amount' => '1200.00',
|
||||
]);
|
||||
$previewResponse->assertRedirect()->assertSessionHasNoErrors();
|
||||
$preview = $previewResponse->getSession()->get('kuka_posting_amount_preview');
|
||||
$this->assertIsArray($preview);
|
||||
$this->assertTrue($preview['is_exact']);
|
||||
$this->assertSame(0, $preview['difference_cents']);
|
||||
$this->assertSame(12, $preview['selected_rows']);
|
||||
$this->assertSame(12, $preview['selected_material_count']);
|
||||
|
||||
$applyResponse = $this->post(route('business.kuka-posting-amount.apply'), [
|
||||
'period' => '2026-10',
|
||||
'target_amount' => '1200.00',
|
||||
'preview_hash' => $preview['preview_hash'],
|
||||
]);
|
||||
$applyResponse->assertRedirect()->assertSessionHasNoErrors();
|
||||
|
||||
$labels = $connection->table('kuka_posting_base_rows')
|
||||
->where('company_id', $this->company->id)
|
||||
->where('period', '2026-10')
|
||||
->orderBy('source_row_number')
|
||||
->get()
|
||||
->map(static function (object $row): string {
|
||||
$values = json_decode((string) $row->source_values, true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
return (string) ($values['过账标签'] ?? '');
|
||||
});
|
||||
$this->assertSame(12, $labels->filter(
|
||||
static fn (string $label): bool => $label === '是',
|
||||
)->count());
|
||||
$this->assertSame(12, $labels->filter(
|
||||
static fn (string $label): bool => $label === '补单(订单四组)',
|
||||
)->count());
|
||||
|
||||
$this->assertDatabaseHas('kuka_posting_base_imports', [
|
||||
'company_id' => $this->company->id,
|
||||
'period' => '2026-10',
|
||||
'posting_target_amount' => '1200.00',
|
||||
'posting_selected_amount' => '1200.00',
|
||||
'posting_difference_amount' => '0.00',
|
||||
'posting_selected_rows' => 12,
|
||||
'posting_material_count' => 12,
|
||||
], 'business_mirror');
|
||||
|
||||
$this->get(route('business.pages.show', [
|
||||
'section' => 'posting-data',
|
||||
'page' => 'kuka-basic-data',
|
||||
'period' => '2026-10',
|
||||
]))
|
||||
->assertOk()
|
||||
->assertSeeText('整月过账金额')
|
||||
->assertSeeText('计算分配方案')
|
||||
->assertSeeText('上次过账 1,200.00');
|
||||
|
||||
@unlink($file);
|
||||
}
|
||||
|
||||
private function workbook(bool $skipFirstStore = false, bool $includeOptionalFields = true): string
|
||||
{
|
||||
$fields = array_values(array_filter(
|
||||
|
||||
106
tests/Unit/Business/KukaPostingAmountSelectionTest.php
Normal file
106
tests/Unit/Business/KukaPostingAmountSelectionTest.php
Normal file
@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Business;
|
||||
|
||||
use App\Business\KukaPostingBase\KukaPostingAmountSelection;
|
||||
use InvalidArgumentException;
|
||||
use Tests\TestCase;
|
||||
|
||||
class KukaPostingAmountSelectionTest extends TestCase
|
||||
{
|
||||
public function test_selects_at_least_one_row_from_each_material_and_matches_exactly(): void
|
||||
{
|
||||
$result = (new KukaPostingAmountSelection())->select([
|
||||
'MAT-A' => [
|
||||
$this->row(1, 10000, '2026-10-01 08:00:00', 2),
|
||||
$this->row(2, 10000, '2026-10-02 08:00:00', 3),
|
||||
],
|
||||
'MAT-B' => [
|
||||
$this->row(3, 20000, '2026-10-01 09:00:00', 4),
|
||||
$this->row(4, 10000, '2026-10-03 09:00:00', 5),
|
||||
],
|
||||
], 30000);
|
||||
|
||||
$this->assertTrue($result['exact']);
|
||||
$this->assertSame(30000, $result['selected_cents']);
|
||||
$this->assertSame(0, $result['difference_cents']);
|
||||
$this->assertSame([1, 3], $result['selected_ids']);
|
||||
$this->assertSame(2, $result['selected_materials']);
|
||||
}
|
||||
|
||||
public function test_same_material_rows_are_selected_from_earliest_shipping_date(): void
|
||||
{
|
||||
$result = (new KukaPostingAmountSelection())->select([
|
||||
'MAT-A' => [
|
||||
$this->row(1, 10000, '2026-10-02 08:00:00', 2),
|
||||
$this->row(2, 20000, '2026-10-01 08:00:00', 3),
|
||||
],
|
||||
'MAT-B' => [
|
||||
$this->row(3, 10000, '2026-10-01 09:00:00', 4),
|
||||
],
|
||||
], 30000);
|
||||
|
||||
$this->assertTrue($result['exact']);
|
||||
$this->assertSame([2, 3], $result['selected_ids']);
|
||||
}
|
||||
|
||||
public function test_auto_calibration_adds_a_later_row_to_reach_the_exact_month_total(): void
|
||||
{
|
||||
$result = (new KukaPostingAmountSelection())->select([
|
||||
'MAT-A' => [
|
||||
$this->row(1, 10000, '2026-10-01 08:00:00', 2),
|
||||
$this->row(2, 10000, '2026-10-02 08:00:00', 3),
|
||||
],
|
||||
'MAT-B' => [
|
||||
$this->row(3, 10000, '2026-10-01 09:00:00', 4),
|
||||
$this->row(4, 10000, '2026-10-02 09:00:00', 5),
|
||||
],
|
||||
], 30000);
|
||||
|
||||
$this->assertTrue($result['exact']);
|
||||
$this->assertSame(3, $result['selected_rows']);
|
||||
$this->assertSame(30000, $result['selected_cents']);
|
||||
}
|
||||
|
||||
public function test_inexact_plan_is_returned_with_a_visible_difference(): void
|
||||
{
|
||||
$result = (new KukaPostingAmountSelection())->select([
|
||||
'MAT-A' => [
|
||||
$this->row(1, 10000, '2026-10-01 08:00:00', 2),
|
||||
$this->row(2, 10000, '2026-10-02 08:00:00', 3),
|
||||
],
|
||||
'MAT-B' => [
|
||||
$this->row(3, 10000, '2026-10-01 09:00:00', 4),
|
||||
$this->row(4, 10000, '2026-10-02 09:00:00', 5),
|
||||
],
|
||||
], 35000);
|
||||
|
||||
$this->assertFalse($result['exact']);
|
||||
$this->assertSame(40000, $result['selected_cents']);
|
||||
$this->assertSame(-5000, $result['difference_cents']);
|
||||
}
|
||||
|
||||
public function test_month_total_below_one_row_per_material_is_rejected(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('每个料号至少选择一行');
|
||||
|
||||
(new KukaPostingAmountSelection())->select([
|
||||
'MAT-A' => [$this->row(1, 10000, '2026-10-01 08:00:00', 2)],
|
||||
'MAT-B' => [$this->row(2, 20000, '2026-10-01 09:00:00', 3)],
|
||||
], 25000);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{id:int,amount_cents:int,date:string,source_row_number:int}
|
||||
*/
|
||||
private function row(int $id, int $amountCents, string $date, int $sourceRowNumber): array
|
||||
{
|
||||
return [
|
||||
'id' => $id,
|
||||
'amount_cents' => $amountCents,
|
||||
'date' => $date,
|
||||
'source_row_number' => $sourceRowNumber,
|
||||
];
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user