CaiWuXiTong/modules/EcommerceFinance/Services/SupplierBookkeepingValuation.php
limeng 8b56efb66f fix(厂家记账): 按财务确认恢复缺文件核价与免扣判定
厂家记账对已确认未发出的单据仍显示待确认;缺月度发货文件时无法继续成本核价;同一快递号的其他发货来源会干扰工单对应商品的运费替代。

本次调整:全部未发出的工单明确不扣款;缺文件且无原单匹配的补偿/全款,保留原小额免记账顺序,按完整工单逐商品数量与当前成本、20%替代运费核价,再和原金额取小值;成本核价排除同号无关商品来源;增加公司级单工单免扣设置,应用财务确认的特例而不扩大到所有缺供应商工单。原单部分匹配、数量含糊、缺成本及运费损耗无记录等情况继续待确认。

修改范围:核价Repository、核价服务、商品组合解析、扣款规则、页面数据服务、对应单元/页面回归及规则文档。无数据库迁移;不改权限、上游、发货重量或发货运费计算。上线仅保存已获财务明确授权的一个工单免扣设置,并备份旧设置,不改原始工单。

验证:Docker 中以 www-data、禁用网络、内存 SQLite 运行相关核价、商品解析、规则、Repository 与页面回归,68 tests / 649 assertions 全通过(96.69秒,PHPUnit峰值121MB)。覆盖50元/40%边界、两轮实付、未发出、同号不同来源、多商品数量、缺项、页面筛选与CSV一致性。生产399条工单只读试算0.51秒、峰值52.5MiB,确认只有预期范围变化,敏感明细未放入Git或PR。
2026-12-06 09:26:54 +08:00

317 lines
20 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Modules\EcommerceFinance\Services;
use Modules\EcommerceFinance\Repositories\SupplierBookkeepingValuationRepository as Repository;
use Throwable;
/** 两轮免记账之后,按原单发货记录核算实际可记账金额。 */
class SupplierBookkeepingValuation
{
/** 只记成本价的供应商:补偿、全款、运费损耗均按发货数量×商品成本价记账,不加运费、不与原金额比较。 */
public const COST_ONLY_SUPPLIERS = ['沐野竹木'];
public function __construct(private readonly Repository $repository) {}
/** @param list<array<string,mixed>> $rows @return list<array<string,mixed>> */
public function apply(array $rows): array
{
$candidates = array_filter($rows, fn ($row) => $this->needsValuation($row));
if ($candidates === []) return $rows;
try {
$shipments = $this->repository->shipmentsFor(array_values($candidates));
$readyMonths = $this->repository->readyMonths();
} catch (Throwable $exception) {
report($exception);
foreach (array_keys($candidates) as $key) $rows[$key] = $this->review($rows[$key], '发货数据暂不可读取,请核对后记账');
return $rows;
}
$byTracking = [];
$byOrder = [];
foreach ($shipments as $shipment) {
$shipment['tracking_numbers'] ??= array_values(array_unique(array_merge(Repository::numbers($shipment['express_no']), Repository::numbers($shipment['old_express_no'] ?? ''))));
$shipment['order_numbers'] ??= Repository::numbers($shipment['trade_no']);
foreach ($shipment['tracking_numbers'] as $reference) $byTracking[$reference][] = $shipment;
foreach ($shipment['order_numbers'] as $reference) $byOrder[$reference][] = $shipment;
}
$skus = [];
foreach ($candidates as $row) {
array_push($skus, ...Repository::numbers(($row['resolved_product_code'] ?? '') !== '' ? $row['resolved_product_code'] : ($row['product_code'] ?? '')));
}
try {
$costs = $this->repository->costsFor(array_values(array_unique($skus)));
} catch (Throwable $exception) {
report($exception);
$costs = [];
}
foreach (array_keys($candidates) as $key) {
$rows[$key] = $this->value($rows[$key], $byTracking, $byOrder, $costs, $readyMonths);
}
return $rows;
}
private function needsValuation(array $row): bool
{
return ($row['deduction_status'] ?? '') === SupplierBookkeepingDeductionRule::STATUS_DEDUCT
&& in_array($row['bookkeeping_type'] ?? '', ['补偿款项', '记账全款', '记账全额', '运费损耗'], true)
&& self::decimal($row['amount'] ?? null)
&& (bccomp((string) $row['amount'], '0', 6) > 0 || $row['bookkeeping_type'] === '运费损耗');
}
private function value(array $row, array $byTracking, array $byOrder, array $costs, array $readyMonths): array
{
[$from, $to] = Repository::window($row);
$row['valuation_window'] = substr($from, 0, 7) . ' 至 ' . substr((string) $row['started_at'], 0, 7);
$missingMonth = Repository::missingMonth($row, $readyMonths);
$tracking = Repository::numbers($row['tracking_no'] ?? '');
$orders = Repository::numbers($row['online_order_no'] ?? '');
if ($missingMonth !== null && $tracking === []) return $this->valueFromWorkOrder($row, $costs, $missingMonth);
$pool = [];
foreach ($tracking !== [] ? $tracking : $orders as $number) {
foreach (($tracking !== [] ? $byTracking : $byOrder)[$number] ?? [] as $shipment) {
// 已完整导入的账期保持原路径;缺文件时仅接受按明确快递号匹配的自动同步包裹。
if (($missingMonth !== null) !== (($shipment['valuation_source'] ?? '') === 'synced')) continue;
if ($shipment['ship_time'] !== null && ($shipment['ship_time'] < $from || $shipment['ship_time'] >= $to)) continue;
if ($tracking !== [] && $orders !== [] && array_intersect($shipment['order_numbers'] ?? [(string) $shipment['trade_no']], $orders) === []) continue;
$pool[$shipment['id']] = $shipment;
}
}
if ($pool === []) return $missingMonth !== null
? $this->valueFromWorkOrder($row, $costs, $missingMonth)
: $this->review($row, '六个月内未匹配到原订单/快递单号的发货记录');
$unshippedPackages = [];
foreach ($pool as $shipment) {
$flag = trim((string) ($shipment['unshipped'] ?? ''));
// 工作平台导出的查找辅助列:#N/A 未命中名单,返回单号则确实未发出。
if ($flag === '' || $flag === '#N/A') continue;
if (str_starts_with($flag, '#')) return $this->review($row, '未发出辅助列存在未识别错误,请核对');
$unshippedPackages[(string) $shipment['source_id']] = true;
}
if ($unshippedPackages !== []) {
$pool = array_filter($pool, static fn ($shipment) => !isset($unshippedPackages[(string) $shipment['source_id']]));
if ($pool === []) {
$row['deduction_status'] = SupplierBookkeepingDeductionRule::STATUS_SKIP;
$row['deduction_basis'] .= ';原单标记未发出,不计厂家扣款';
return $row;
}
$row['deduction_basis'] .= ';已排除未发出包裹';
}
foreach ($pool as $shipment) {
if (isset($shipment['valuation_error'])) return $this->review($row, $shipment['valuation_error']);
}
$matchedReferences = [];
foreach ($pool as $shipment) array_push($matchedReferences, ...($tracking !== [] ? ($shipment['tracking_numbers'] ?? [$shipment['express_no']]) : ($shipment['order_numbers'] ?? [$shipment['trade_no']])));
if (array_diff($tracking !== [] ? $tracking : $orders, $matchedReferences) !== []) {
if ($unshippedPackages !== []) return $this->review($row, '原单号包含未发出包裹,暂不能按部分金额记账');
return $this->review($row, '原单号包含未匹配发货记录,暂不能按部分金额记账');
}
$packages = [];
$quantity = '0';
$cost = '0';
$wanted = array_fill_keys(array_map([Repository::class, 'sku'], Repository::numbers(($row['resolved_product_code'] ?? '') !== '' ? $row['resolved_product_code'] : ($row['product_code'] ?? ''))), false);
$costOnly = self::costOnlyMode($row);
if ($costOnly === null) return $this->review($row, '多个供应商中含只记成本价的' . implode('、', self::COST_ONLY_SUPPLIERS) . ',请人工确认');
$freightOnly = !$costOnly && $row['bookkeeping_type'] === '运费损耗';
$lines = [];
if (!$freightOnly && $wanted === []) return $this->review($row, '工单没有商品编码,无法匹配成本');
if (!$freightOnly) {
// 同一快递号可对应不同发货单;仅核算包含工单商品的发货单,不借用同号配件单的运费。
$relevantPackages = [];
foreach ($pool as $shipment) {
if (array_intersect(array_keys($wanted), array_map([Repository::class, 'sku'], Repository::numbers($shipment['barcode']))) !== []) {
$relevantPackages[(string) $shipment['source_id']] = true;
}
}
if ($relevantPackages !== []) {
$pool = array_filter($pool, static fn ($shipment) => isset($relevantPackages[(string) $shipment['source_id']]));
$matchedReferences = [];
foreach ($pool as $shipment) array_push($matchedReferences, ...($tracking !== [] ? ($shipment['tracking_numbers'] ?? [$shipment['express_no']]) : ($shipment['order_numbers'] ?? [$shipment['trade_no']])));
if (array_diff($tracking !== [] ? $tracking : $orders, $matchedReferences) !== []) return $this->review($row, '原单号包含未匹配工单商品的包裹,暂不能按部分金额记账');
}
}
foreach ($pool as $shipment) {
if ($shipment['ship_time'] === null) return $this->review($row, '匹配发货日期无效,请核对');
if (trim((string) $shipment['express_no']) === '' || count(Repository::numbers($shipment['express_no'])) !== 1) return $this->review($row, '包裹快递单号缺失或不唯一,请核对');
$package = (string) $shipment['source_id'];
$packages[$package] ??= ['amount' => '0', 'has_freight' => false];
if (!$costOnly && $shipment['freight'] !== null && $shipment['freight'] !== '') {
if (!self::decimal($shipment['freight'])) return $this->review($row, '原单运费无效,请核对');
// 汇总表的包裹运费可能随每件商品重复关联,只取一次;冲突值不能相加。
if ($packages[$package]['has_freight']
&& bccomp($packages[$package]['amount'], (string) $shipment['freight'], 6) !== 0) {
return $this->review($row, '同一包裹运费不一致,请核对');
}
$packages[$package]['amount'] = (string) $shipment['freight'];
$packages[$package]['has_freight'] = true;
}
}
$estimatedPackages = $costOnly ? [] : array_filter($packages, static fn ($package) => !$package['has_freight'] || bccomp($package['amount'], '0', 6) === 0);
if ($freightOnly && $estimatedPackages !== []) {
$shippedSkus = [];
foreach ($pool as $shipment) array_push($shippedSkus, ...array_map([Repository::class, 'sku'], Repository::numbers($shipment['barcode'])));
if (array_diff(array_keys($wanted), $shippedSkus) !== []) return $this->review($row, '原单发货明细未匹配全部工单商品,无法估算运费');
}
$packageCosts = [];
$usedBundleQuantity = false;
foreach ($pool as $shipment) {
$package = (string) $shipment['source_id'];
if ($freightOnly && !isset($estimatedPackages[$package])) continue;
if ($wanted === []) return $this->review($row, '工单没有商品编码,无法匹配替代运费所需成本');
$components = array_values(array_unique(array_map([Repository::class, 'sku'], Repository::numbers($shipment['barcode']))));
$bundle = count($components) > 1;
foreach ($components as $sku) {
if (!array_key_exists($sku, $wanted)) continue;
if ($costOnly && $bundle) return $this->review($row, '组合装缺少逐商品实际发货数量,无法按成本价记账');
// 组合装导出只有合计数量,财务确认按各商品条码1件核价。
$lineQuantity = $bundle ? '1' : (string) ($shipment['qty'] ?? '');
if (!self::decimal($lineQuantity) || bccomp($lineQuantity, '0', 6) <= 0) {
return $this->review($row, '匹配发货数量缺失或无效');
}
$usedBundleQuantity = $usedBundleQuantity || $bundle;
$lineKey = $package . '|' . $sku;
if (isset($lines[$lineKey])) {
if (bccomp($lines[$lineKey], $lineQuantity, 6) !== 0) return $this->review($row, '同一包裹商品数量不一致,请核对');
continue;
}
$lines[$lineKey] = $lineQuantity;
$quantity = bcadd($quantity, $lineQuantity, 6);
$price = $costs[$sku] ?? null;
if (!self::decimal($price) || bccomp((string) $price, '0', 6) <= 0) return $this->review($row, '商品成本价缺失或为0:' . $sku);
$lineCost = bcmul((string) $price, $lineQuantity, 6);
$cost = bcadd($cost, $lineCost, 6);
$packageCosts[$package] = bcadd($packageCosts[$package] ?? '0', $lineCost, 6);
$wanted[$sku] = true;
}
}
if (!$freightOnly && in_array(false, $wanted, true)) return $this->review($row, '原单发货明细未匹配全部工单商品');
foreach (array_keys($estimatedPackages) as $package) {
if (!isset($packageCosts[$package])) return $this->review($row, '原单发货商品未匹配替代运费所需成本');
$packages[$package]['amount'] = bcmul($packageCosts[$package], '0.2', 6);
$packages[$package]['has_freight'] = true;
}
$freight = '0';
foreach ($costOnly ? [] : $packages as $package) {
if (!$package['has_freight']) return $this->review($row, '原单运费尚未补齐,不能按0记账');
$freight = bcadd($freight, $package['amount'], 6);
}
$row['matched_freight'] = self::money($freight);
$row['matched_quantity'] = $freightOnly && $estimatedPackages === [] ? '' : rtrim(rtrim($quantity, '0'), '.');
$row['matched_tracking_no'] = implode("\n", array_values(array_unique(array_column($pool, 'express_no'))));
if ($costOnly) {
$row['matched_cost'] = self::money($cost);
$row['matched_freight'] = null;
$row['amount'] = self::money($cost);
$basis = implode('、', self::COST_ONLY_SUPPLIERS) . '只记成本价:按发货数量×商品成本价记账,不含运费';
} elseif ($freightOnly) {
$row['amount'] = self::money($freight);
if ($estimatedPackages !== []) {
$row['matched_cost'] = self::money($cost);
$basis = '运费损耗:原单运费缺失或为0,按对应商品成本合计×0.2替代运费';
if (count($estimatedPackages) < count($packages)) $basis .= ',另加其余包裹实际运费';
} else {
$basis = '运费损耗按原单实际运费记账';
}
} else {
$row['matched_cost'] = self::money($cost);
$ceiling = self::money(bcadd($cost, $freight, 6));
$freightLabel = $estimatedPackages === [] ? '实际运费' : '运费';
if (bccomp((string) $row['amount'], $ceiling, 2) > 0) {
$row['amount'] = $ceiling;
$basis = '原记账金额大于商品成本+' . $freightLabel . ',按成本+运费记账';
} else {
$basis = '原记账金额不大于商品成本+' . $freightLabel . ',保留记账金额';
}
if ($estimatedPackages !== []) $basis .= ';原单运费缺失或为0,按商品成本×0.2替代运费';
}
if ($usedBundleQuantity) $basis .= ';组合装按各条码1件计';
if ($missingMonth !== null) $basis .= ';按系统同步发货明细核价(原快递单号完整匹配)';
$row['deduction_basis'] .= ';' . $basis;
$row['remark'] = trim((string) ($row['remark'] ?? '')) === '' ? $basis : $row['remark'] . "\n" . $basis;
if (bccomp((string) $row['amount'], '0', 2) === 0) $row['deduction_status'] = SupplierBookkeepingDeductionRule::STATUS_SKIP;
return $row;
}
/** 仅在缺月文件且未匹配到原单时,按明确的工单商品数量核价;不采用部分发货记录。 */
private function valueFromWorkOrder(array $row, array $costs, string $missingMonth): array
{
$prefix = '六个月发货文件尚未补齐:' . $missingMonth;
if (!in_array($row['bookkeeping_type'], ['补偿款项', '记账全款', '记账全额'], true)) return $this->review($row, $prefix);
$tracking = Repository::numbers($row['tracking_no'] ?? '');
try {
$unshipped = $this->repository->unshippedTracking($tracking);
} catch (Throwable $exception) {
report($exception);
return $this->review($row, $prefix . ';未发出名单暂不可读取');
}
$hits = array_intersect($tracking, $unshipped);
if ($hits !== []) {
if (count($hits) !== count($tracking)) return $this->review($row, '原单号包含未发出包裹,暂不能按部分金额记账');
$row['deduction_status'] = SupplierBookkeepingDeductionRule::STATUS_SKIP;
$row['deduction_basis'] .= ';原单标记未发出,不计厂家扣款';
return $row;
}
$codes = array_map([Repository::class, 'sku'], preg_split('/[\r\n,,、;;]+/u', trim((string) ($row['product_code'] ?? ''))) ?: []);
$quantities = preg_split('/[\r\n,,、;;]+/u', trim((string) ($row['product_quantity'] ?? ''))) ?: [];
if ($codes === [] || count($codes) !== count($quantities)) return $this->review($row, $prefix . ';工单缺少逐商品数量');
$wanted = array_map([Repository::class, 'sku'], Repository::numbers(($row['resolved_product_code'] ?? '') ?: ($row['product_code'] ?? '')));
$counted = []; $cost = '0'; $quantity = '0';
foreach ($codes as $index => $code) {
$qty = trim($quantities[$index]);
if ($code === '' || !self::decimal($qty) || bccomp($qty, '0', 6) <= 0) return $this->review($row, $prefix . ';工单商品数量无效');
$parts = in_array($code, $wanted, true) ? [$code => '1'] : SupplierBookkeepingProductResolver::encodedQuantities($code);
if ($parts === [] || array_diff(array_keys($parts), $wanted) !== []) return $this->review($row, $prefix . ';无法还原工单逐商品数量');
foreach ($parts as $sku => $units) {
$price = $costs[$sku] ?? null;
if (!self::decimal($price) || bccomp($price, '0', 6) <= 0) return $this->review($row, $prefix . ';商品成本价缺失或为0:' . $sku);
$lineQuantity = bcmul($qty, $units, 6);
$quantity = bcadd($quantity, $lineQuantity, 6);
$cost = bcadd($cost, bcmul($lineQuantity, $price, 6), 6);
$counted[$sku] = true;
}
}
if (array_diff($wanted, array_keys($counted)) !== []) return $this->review($row, $prefix . ';未匹配全部工单商品');
$costOnly = self::costOnlyMode($row);
if ($costOnly === null) return $this->review($row, '多个供应商中含只记成本价的' . implode('、', self::COST_ONLY_SUPPLIERS) . ',请人工确认');
$freight = $costOnly ? '0' : bcmul($cost, '0.2', 6);
$ceiling = self::money(bcadd($cost, $freight, 6));
if ($costOnly || bccomp($row['amount'], $ceiling, 2) > 0) $row['amount'] = $ceiling;
$row['matched_cost'] = self::money($cost);
$row['matched_freight'] = $costOnly ? null : self::money($freight);
$row['matched_quantity'] = rtrim(rtrim($quantity, '0'), '.');
$basis = $prefix . ';按工单逐商品数量×商品资料成本核价;' . ($costOnly
? '沐野竹木只记成本价,不含运费'
: '原单运费缺失或为0,按商品成本×0.2替代运费;按成本+运费与原记账金额取小值');
$row['deduction_basis'] .= ';' . $basis;
$row['remark'] = trim((string) ($row['remark'] ?? '')) === '' ? $basis : $row['remark'] . "\n" . $basis;
return $row;
}
/** true=全部为只记成本价供应商;false=不含;null=与其他供应商混合,需人工确认。 */
private static function costOnlyMode(array $row): ?bool
{
$suppliers = array_values(array_unique(array_filter(array_map('trim', explode("\n", (string) ($row['supplier'] ?? ''))), static fn ($name) => $name !== '')));
$hits = array_intersect($suppliers, self::COST_ONLY_SUPPLIERS);
if ($hits === []) return false;
return count($hits) === count($suppliers) ? true : null;
}
private function review(array $row, string $reason): array
{
$row['deduction_status'] = SupplierBookkeepingDeductionRule::STATUS_REVIEW;
$row['deduction_basis'] .= ';' . $reason;
return $row;
}
private static function decimal(mixed $value): bool
{
return $value !== null && preg_match('/^\d+(?:\.\d{1,6})?$/D', (string) $value) === 1;
}
private static function money(string $value): string
{
return bcadd($value, '0.005', 2);
}
}