384 lines
15 KiB
PHP
384 lines
15 KiB
PHP
<?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'),
|
|
);
|
|
}
|
|
}
|