465 lines
16 KiB
PHP
465 lines
16 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
use DateTimeImmutable;
|
||
use Illuminate\Validation\ValidationException;
|
||
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
|
||
use Throwable;
|
||
|
||
/**
|
||
* 按月处理历史未定价:先用价格快照匹配历史池,再把当月新增未定价补入历史池。
|
||
*/
|
||
class PayablesUnpricedCycleProcessor
|
||
{
|
||
public const DELIVERY_HISTORY_DATASET = 'final:supplier:delivery-unpriced';
|
||
|
||
public const RETURN_HISTORY_DATASET = 'final:supplier:return-unpriced';
|
||
|
||
public const DELIVERY_PRICED_DATASET = 'final:supplier:previous-unpriced-current-priced-delivery';
|
||
|
||
public const RETURN_PRICED_DATASET = 'final:supplier:previous-unpriced-current-priced-return';
|
||
|
||
public const DELIVERY_RECONCILIATION_DATASET = 'final:supplier:payment-reconciliation';
|
||
|
||
public const RETURN_RECONCILIATION_DATASET = 'final:supplier:return-reconciliation';
|
||
|
||
public const RUN_DATASET = 'final:supplier:unpriced-pricing-cycle-runs';
|
||
|
||
public function __construct(
|
||
private readonly SupplierPayableOverrideStore $store,
|
||
) {
|
||
}
|
||
|
||
/**
|
||
* @return array<string,mixed>
|
||
*/
|
||
public function process(
|
||
string $priceFile,
|
||
string $period,
|
||
string $cutoff,
|
||
int $companyId,
|
||
?int $userId = null,
|
||
): array {
|
||
if (preg_match('/^\d{4}-\d{2}$/', $period) !== 1) {
|
||
throw ValidationException::withMessages(['period' => '账期必须为 YYYY-MM 格式。']);
|
||
}
|
||
if (! is_file($priceFile)) {
|
||
throw ValidationException::withMessages(['price_file' => '价格文件不存在。']);
|
||
}
|
||
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $cutoff) !== 1) {
|
||
throw ValidationException::withMessages(['cutoff' => '价格截止日必须为 YYYY-MM-DD 格式。']);
|
||
}
|
||
|
||
$completedRun = $this->store->findLatestRow(self::RUN_DATASET, [
|
||
'summary_month' => $period,
|
||
'status' => 'completed',
|
||
], $companyId);
|
||
if ($completedRun !== null) {
|
||
throw ValidationException::withMessages([
|
||
'period' => "账期 {$period} 已完成定价批次,不能重复处理。",
|
||
]);
|
||
}
|
||
|
||
$priceMap = $this->readPriceMap($priceFile, $cutoff);
|
||
if ($priceMap === []) {
|
||
throw ValidationException::withMessages(['price_file' => '价格文件中没有可用定价记录。']);
|
||
}
|
||
|
||
$deliveryHistory = $this->store->listRows(self::DELIVERY_HISTORY_DATASET, $companyId);
|
||
$returnHistory = $this->store->listRows(self::RETURN_HISTORY_DATASET, $companyId);
|
||
|
||
$deliveryMatched = $this->matchRows(
|
||
$deliveryHistory,
|
||
'barCode',
|
||
'qty',
|
||
'unitPrice',
|
||
'amount',
|
||
$period,
|
||
$priceMap,
|
||
'delivery',
|
||
);
|
||
$returnMatched = $this->matchRows(
|
||
$returnHistory,
|
||
'barcode',
|
||
'qty',
|
||
'unit_price',
|
||
'amount',
|
||
$period,
|
||
$priceMap,
|
||
'return',
|
||
);
|
||
|
||
$newDelivery = $this->newDeliveryUnpriced(
|
||
$this->store->listRows(self::DELIVERY_RECONCILIATION_DATASET, $companyId),
|
||
$period,
|
||
);
|
||
$newReturn = $this->newReturnUnpriced(
|
||
$this->store->listRows(self::RETURN_RECONCILIATION_DATASET, $companyId),
|
||
$period,
|
||
);
|
||
|
||
$summary = [
|
||
'period' => $period,
|
||
'cutoff' => $cutoff,
|
||
'price_file' => basename($priceFile),
|
||
'price_codes' => count($priceMap),
|
||
'matched_delivery_rows' => count($deliveryMatched['rows']),
|
||
'matched_return_rows' => count($returnMatched['rows']),
|
||
'history_delivery_remaining' => count($deliveryHistory) - count($deliveryMatched['source_keys']),
|
||
'history_return_remaining' => count($returnHistory) - count($returnMatched['source_keys']),
|
||
'new_delivery_rows' => count($newDelivery),
|
||
'new_return_rows' => count($newReturn),
|
||
];
|
||
|
||
$this->store->transaction(function () use (
|
||
$companyId,
|
||
$userId,
|
||
$summary,
|
||
$deliveryMatched,
|
||
$returnMatched,
|
||
$newDelivery,
|
||
$newReturn,
|
||
): void {
|
||
$this->store->saveBatch(
|
||
self::DELIVERY_PRICED_DATASET,
|
||
$deliveryMatched['rows'],
|
||
$companyId,
|
||
$userId,
|
||
'pricing-cycle',
|
||
);
|
||
$this->store->saveBatch(
|
||
self::RETURN_PRICED_DATASET,
|
||
$returnMatched['rows'],
|
||
$companyId,
|
||
$userId,
|
||
'pricing-cycle',
|
||
);
|
||
|
||
$this->store->deleteBatch(
|
||
self::DELIVERY_HISTORY_DATASET,
|
||
$deliveryMatched['source_keys'],
|
||
$companyId,
|
||
$userId,
|
||
'pricing-cycle',
|
||
);
|
||
$this->store->deleteBatch(
|
||
self::RETURN_HISTORY_DATASET,
|
||
$returnMatched['source_keys'],
|
||
$companyId,
|
||
$userId,
|
||
'pricing-cycle',
|
||
);
|
||
|
||
// 当月新增未定价必须在本月匹配完成后追加,留待下个账期匹配。
|
||
$this->store->saveBatch(
|
||
self::DELIVERY_HISTORY_DATASET,
|
||
$newDelivery,
|
||
$companyId,
|
||
$userId,
|
||
'period-carry',
|
||
);
|
||
$this->store->saveBatch(
|
||
self::RETURN_HISTORY_DATASET,
|
||
$newReturn,
|
||
$companyId,
|
||
$userId,
|
||
'period-carry',
|
||
);
|
||
|
||
$this->store->saveBatch(
|
||
self::RUN_DATASET,
|
||
[
|
||
'id:cycle:' . $summary['period'] => $summary + [
|
||
'summary_month' => $summary['period'],
|
||
'status' => 'completed',
|
||
'completed_at' => now()->toIso8601String(),
|
||
],
|
||
],
|
||
$companyId,
|
||
$userId,
|
||
'pricing-cycle',
|
||
);
|
||
});
|
||
|
||
return $summary;
|
||
}
|
||
|
||
/**
|
||
* @param list<array<string,mixed>> $rows
|
||
* @param array<string,array{price:float,start:string}> $priceMap
|
||
* @return array{rows:array<string,array<string,mixed>>,source_keys:list<string>}
|
||
*/
|
||
private function matchRows(
|
||
array $rows,
|
||
string $codeField,
|
||
string $quantityField,
|
||
string $priceField,
|
||
string $amountField,
|
||
string $period,
|
||
array $priceMap,
|
||
string $kind,
|
||
): array {
|
||
$matched = [];
|
||
$sourceKeys = [];
|
||
|
||
foreach ($rows as $row) {
|
||
$code = $this->normalizeCode($row[$codeField] ?? null);
|
||
if ($code === '' || ! isset($priceMap[$code])) {
|
||
continue;
|
||
}
|
||
|
||
$quantity = $this->number($row[$quantityField] ?? null);
|
||
if ($quantity === null) {
|
||
throw ValidationException::withMessages([
|
||
'unpriced' => "{$kind}记录 {$code} 的数量无效,无法计算金额。",
|
||
]);
|
||
}
|
||
|
||
$sourceKey = (string) ($row['_action_key'] ?? '');
|
||
if ($sourceKey === '') {
|
||
continue;
|
||
}
|
||
|
||
$price = (float) $priceMap[$code]['price'];
|
||
$row[$priceField] = $this->formatPrice($price);
|
||
$row[$amountField] = number_format($quantity * $price, 2, '.', '');
|
||
$row['_accounting_period'] = $period;
|
||
$row['_matched_product_code'] = $code;
|
||
$row['_price_effective_start'] = $priceMap[$code]['start'];
|
||
unset($row['_action_key']);
|
||
|
||
$recordKey = 'id:cycle:' . $period . ':' . $kind . ':' . hash('sha256', $sourceKey);
|
||
$matched[$recordKey] = $row;
|
||
$sourceKeys[] = $sourceKey;
|
||
}
|
||
|
||
return ['rows' => $matched, 'source_keys' => $sourceKeys];
|
||
}
|
||
|
||
/**
|
||
* @param list<array<string,mixed>> $rows
|
||
* @return array<string,array<string,mixed>>
|
||
*/
|
||
private function newDeliveryUnpriced(array $rows, string $period): array
|
||
{
|
||
$carried = [];
|
||
foreach ($rows as $row) {
|
||
if (trim((string) ($row['summary_month'] ?? '')) !== $period
|
||
|| ! $this->isUnpriced($row, 'amount', 'guessAmount')) {
|
||
continue;
|
||
}
|
||
|
||
$sourceKey = (string) ($row['_action_key'] ?? '');
|
||
$carried['id:carry:' . hash('sha256', self::DELIVERY_RECONCILIATION_DATASET . ':' . $sourceKey)] = [
|
||
'transactionNo' => $row['purchaseNo'] ?? '',
|
||
'distributionNo' => $row['stockNo'] ?? '',
|
||
'date' => $row['date'] ?? '',
|
||
'supplier' => $row['supplier'] ?? '',
|
||
'sku' => $row['skuCode'] ?? '',
|
||
'barCode' => $row['productCode'] ?? '',
|
||
'skuName' => $row['skuName'] ?? '',
|
||
'qty' => $row['qty'] ?? '',
|
||
'unitPrice' => $row['unitPrice'] ?? '',
|
||
'amount' => $row['amount'] ?? '',
|
||
'guessUnitPrice' => $row['guessUnitPrice'] ?? '',
|
||
'guessAmount' => $row['guessAmount'] ?? '',
|
||
'supplier_barcode' => $row['supplierGoodsCode'] ?? '',
|
||
'remark' => $row['remark'] ?? '',
|
||
'warehouse' => $row['warehouse'] ?? '',
|
||
'sendTime' => '',
|
||
'expressName' => $row['expressName'] ?? '',
|
||
'expressNo' => $row['expressNo'] ?? '',
|
||
'unsent' => $row['unsent'] ?? '',
|
||
'_source_values' => array_diff_key($row, ['_action_key' => true]),
|
||
];
|
||
}
|
||
|
||
return $carried;
|
||
}
|
||
|
||
/**
|
||
* @param list<array<string,mixed>> $rows
|
||
* @return array<string,array<string,mixed>>
|
||
*/
|
||
private function newReturnUnpriced(array $rows, string $period): array
|
||
{
|
||
$carried = [];
|
||
foreach ($rows as $row) {
|
||
if (trim((string) ($row['summary_month'] ?? '')) !== $period
|
||
|| ! $this->isUnpriced($row, 'amount', 'guess_amount')) {
|
||
continue;
|
||
}
|
||
|
||
$sourceKey = (string) ($row['_action_key'] ?? '');
|
||
$carried['id:carry:' . hash('sha256', self::RETURN_RECONCILIATION_DATASET . ':' . $sourceKey)] = [
|
||
'send_time' => $row['send_time'] ?? '',
|
||
'supplier' => $row['supplier'] ?? '',
|
||
'barcode' => $row['barcode'] ?? '',
|
||
'sku_name' => $row['sku_name'] ?? '',
|
||
'qty' => $row['qty'] ?? '',
|
||
'unit_price' => $row['unit_price'] ?? '',
|
||
'amount' => $row['amount'] ?? '',
|
||
'guess_unit_price' => $row['guess_unit_price'] ?? '',
|
||
'guess_amount' => $row['guess_amount'] ?? '',
|
||
'supplier_barcode' => $row['supplier_barcode'] ?? '',
|
||
'deduction_barcode' => '',
|
||
'remark' => $row['remark'] ?? '',
|
||
'order_no' => '',
|
||
'warehouse' => $row['warehouse'] ?? '',
|
||
'express_no' => $row['express_no'] ?? '',
|
||
'send_time_secondary' => '',
|
||
'_source_values' => array_diff_key($row, ['_action_key' => true]),
|
||
];
|
||
}
|
||
|
||
return $carried;
|
||
}
|
||
|
||
private function isUnpriced(array $row, string $amountField, string $guessAmountField): bool
|
||
{
|
||
$amount = $this->number($row[$amountField] ?? null);
|
||
$guessAmount = $this->number($row[$guessAmountField] ?? null);
|
||
|
||
return $guessAmount !== null
|
||
&& $guessAmount > 0
|
||
&& ($amount === null || $amount == 0.0);
|
||
}
|
||
|
||
/**
|
||
* @return array<string,array{price:float,start:string}>
|
||
*/
|
||
private function readPriceMap(string $path, string $cutoff): array
|
||
{
|
||
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
|
||
$reader = PayablesWorkbookStreamReader::forFile($path, $extension);
|
||
$headers = null;
|
||
$latest = [];
|
||
$cutoffAt = new DateTimeImmutable($cutoff . ' 23:59:59');
|
||
|
||
try {
|
||
foreach ($reader->rows(0) as $rowNumber => $row) {
|
||
if ($headers === null) {
|
||
$candidate = $this->priceHeaders($row);
|
||
if ($candidate !== null) {
|
||
$headers = $candidate;
|
||
} elseif ($rowNumber > 20) {
|
||
break;
|
||
}
|
||
continue;
|
||
}
|
||
|
||
$code = $this->normalizeCode($row[$headers['code']] ?? null);
|
||
$price = $this->number($row[$headers['price']] ?? null);
|
||
$start = $this->date($row[$headers['start']] ?? null);
|
||
$end = $this->date($row[$headers['end']] ?? null);
|
||
$completed = $this->date($row[$headers['completed'] ?? -1] ?? null);
|
||
if ($code === '' || $price === null || $start === null
|
||
|| $start > $cutoffAt || ($end !== null && $end < $cutoffAt)) {
|
||
continue;
|
||
}
|
||
|
||
$sortKey = implode('|', [
|
||
$start->format('Y-m-d H:i:s'),
|
||
$completed?->format('Y-m-d H:i:s') ?? '',
|
||
str_pad((string) $rowNumber, 9, '0', STR_PAD_LEFT),
|
||
]);
|
||
if (! isset($latest[$code]) || $sortKey > $latest[$code]['sort']) {
|
||
$latest[$code] = [
|
||
'sort' => $sortKey,
|
||
'price' => $price,
|
||
'start' => $start->format('Y-m-d H:i:s'),
|
||
];
|
||
}
|
||
}
|
||
} catch (Throwable) {
|
||
throw ValidationException::withMessages([
|
||
'price_file' => '无法读取价格文件,请确认文件格式和表头正确。',
|
||
]);
|
||
}
|
||
|
||
return array_map(
|
||
static fn (array $entry): array => [
|
||
'price' => $entry['price'],
|
||
'start' => $entry['start'],
|
||
],
|
||
$latest,
|
||
);
|
||
}
|
||
|
||
/**
|
||
* @return array{code:int,price:int,start:int,end:int,completed:?int}|null
|
||
*/
|
||
private function priceHeaders(array $row): ?array
|
||
{
|
||
$normalized = [];
|
||
foreach ($row as $index => $value) {
|
||
$normalized[$this->header($value)] = (int) $index;
|
||
}
|
||
|
||
$code = $normalized['条形码'] ?? $normalized['商品编码'] ?? null;
|
||
$price = $normalized['变价后价格'] ?? $normalized['定价'] ?? null;
|
||
$start = $normalized['生效开始时间'] ?? null;
|
||
if ($code === null || $price === null || $start === null) {
|
||
return null;
|
||
}
|
||
|
||
return [
|
||
'code' => $code,
|
||
'price' => $price,
|
||
'start' => $start,
|
||
'end' => $normalized['生效结束时间'] ?? -1,
|
||
'completed' => $normalized['流程完成时间'] ?? null,
|
||
];
|
||
}
|
||
|
||
private function header(mixed $value): string
|
||
{
|
||
return mb_strtolower((string) preg_replace('/[\s\x{FEFF}_\-()()]+/u', '', trim((string) $value)));
|
||
}
|
||
|
||
private function normalizeCode(mixed $value): string
|
||
{
|
||
if ($value === null) {
|
||
return '';
|
||
}
|
||
if (is_float($value) && floor($value) === $value) {
|
||
return (string) (int) $value;
|
||
}
|
||
|
||
return trim((string) $value);
|
||
}
|
||
|
||
private function number(mixed $value): ?float
|
||
{
|
||
if ($value === null || trim((string) $value) === '') {
|
||
return null;
|
||
}
|
||
$normalized = str_replace([',', ',', '¥', '¥'], '', trim((string) $value));
|
||
|
||
return is_numeric($normalized) ? (float) $normalized : null;
|
||
}
|
||
|
||
private function date(mixed $value): ?DateTimeImmutable
|
||
{
|
||
if ($value === null || trim((string) $value) === '') {
|
||
return null;
|
||
}
|
||
if (is_numeric($value)) {
|
||
$date = ExcelDate::excelToDateTimeObject((float) $value);
|
||
|
||
return DateTimeImmutable::createFromMutable($date);
|
||
}
|
||
try {
|
||
return new DateTimeImmutable((string) $value);
|
||
} catch (Throwable) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
private function formatPrice(float $price): string
|
||
{
|
||
return rtrim(rtrim(number_format($price, 4, '.', ''), '0'), '.');
|
||
}
|
||
}
|