CaiWuXiTong/modules/EcommerceFinance/Repositories/SupplierBookkeepingValuationRepository.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

223 lines
11 KiB
PHP
Raw Permalink 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\Repositories;
use App\Support\UnshippedWaybills;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
use Modules\EcommerceFinance\Services\SupplierBookkeepingShippingImporter as Shipping;
use RuntimeException;
use Throwable;
/** 厂家记账只读核价:月度导出/原单自动同步明细 + 当前普通商品资料成本。 */
class SupplierBookkeepingValuationRepository
{
public function __construct(
private readonly GenericBusinessMirrorRepository $mirror,
private readonly BusinessMirrorDatasetRegistry $datasets,
) {}
/** @return list<array<string,mixed>> */
public function shipmentsFor(array $rows): array
{
if ($rows === []) return [];
$db = $this->mirror->connection();
$from = null;
$to = null;
$tracking = [];
$orders = [];
foreach ($rows as $row) {
[$start, $end] = self::window($row);
$from = $from === null || $start < $from ? $start : $from;
$to = $to === null || $end > $to ? $end : $to;
$numbers = self::numbers($row['tracking_no'] ?? '');
if ($numbers !== []) {
array_push($tracking, ...$numbers);
} else {
array_push($orders, ...self::numbers($row['online_order_no'] ?? ''));
}
}
$found = [];
// 只读每月已完成的代次;单号独立索引,合并订单也按完整单号匹配。
foreach (['tracking' => $tracking, 'order' => $orders] as $kind => $values) {
foreach (array_chunk(array_values(array_unique($values)), 150) as $chunk) {
$query = $db->table(Shipping::REFS . ' AS f')
->join(Shipping::ROWS . ' AS r', function ($join) {
$join->on('r.generation', '=', 'f.generation')->on('r.source_row', '=', 'f.source_row');
})
->join(Shipping::MONTHS . ' AS m', 'm.active_generation', '=', 'r.generation')
->where('f.kind', $kind)->whereIn('f.reference', $chunk)
->where('m.source_month', '>=', substr($from, 0, 10))->where('m.source_month', '<', substr($to, 0, 10))
->where(function ($q) use ($from, $to) {
$q->whereNull('r.ship_time')->orWhere(function ($q) use ($from, $to) {
$q->where('r.ship_time', '>=', $from)->where('r.ship_time', '<', $to);
});
})->select('r.*');
foreach ($query->cursor() as $record) {
$shipment = (array) $record;
$shipment['id'] = $record->generation . ':' . $record->source_row;
$shipment['tracking_numbers'] = array_values(array_unique(array_merge(self::numbers($record->express_no), self::numbers($record->old_express_no))));
$shipment['order_numbers'] = self::numbers($record->trade_no);
$shipment['source_id'] = hash('sha256', self::identifier($record->express_no) . '|' . $record->package_no);
$found[$shipment['id']] = $shipment;
if (count($found) > 20000) throw new RuntimeException('匹配发货记录过多,须缩小工单范围');
}
}
}
try {
$synced = $this->syncedShipmentsFor($rows);
} catch (Throwable $exception) {
report($exception);
$synced = [];
}
return array_merge(array_values($found), $synced);
}
/** 缺月度文件时,只为有明确快递号的工单读取现有自动同步明细,不按订单借用其他包裹。 */
private function syncedShipmentsFor(array $rows): array
{
$months = $this->readyMonths();
$tracking = $orders = [];
$from = $to = null;
foreach ($rows as $row) {
if (self::missingMonth($row, $months) === null) continue;
$numbers = self::numbers($row['tracking_no'] ?? '');
if ($numbers === []) continue;
array_push($tracking, ...$numbers);
array_push($orders, ...self::numbers($row['online_order_no'] ?? ''));
[$start, $end] = self::window($row);
$from = $from === null || $start < $from ? $start : $from;
$to = $to === null || $end > $to ? $end : $to;
}
if ($tracking === []) return [];
$db = DB::connection((string) config('jushuitan.connection', 'jushuitan_local'));
$schema = $db->getSchemaBuilder();
if (!$schema->hasTable('jst_oms_shipping') || !$schema->hasTable('jst_sync_state')
|| !$db->table('jst_sync_state')->where('dataset_key', 'jst.sctrade')->whereNotNull('last_succeeded_at')->exists()
|| !app(UnshippedWaybills::class)->connection()->getSchemaBuilder()->hasTable('courier_unshipped_waybills')) return [];
$wanted = array_fill_keys($tracking, true);
$trackingValues = [];
foreach (array_keys($wanted) as $number) array_push($trackingValues, (string) $number, '@' . $number);
$found = [];
// express_no/trade_no 均有现有索引;换单前号只在订单定点候选中核对,避免扫描未索引的 front_no。
foreach (['express_no' => $trackingValues, 'trade_no' => $orders] as $column => $values) {
foreach (array_chunk(array_values(array_unique($values)), 150) as $chunk) {
$query = $db->table('jst_oms_shipping')->whereIn($column, $chunk)
->where('ship_time', '>=', $from)->where('ship_time', '<', $to)
->select(['id', 'source_id', 'express_no', 'front_no', 'trade_no', 'barcode', 'qty', 'freight', 'ship_time', 'pkg_count']);
foreach ($query->cursor() as $record) {
$references = array_values(array_unique(array_merge(self::numbers($record->express_no), self::numbers($record->front_no))));
if (array_intersect($references, array_keys($wanted)) === []) continue;
$shipment = (array) $record;
$shipment['id'] = 'synced:' . $record->id;
$shipment['source_id'] = 'synced:' . $record->source_id;
$shipment['valuation_source'] = 'synced';
$shipment['tracking_numbers'] = $references;
$shipment['order_numbers'] = self::numbers($record->trade_no);
$found[$shipment['id']] = $shipment;
if (count($found) > 20000) throw new RuntimeException('匹配发货记录过多,须缩小工单范围');
}
}
}
$unshipped = app(UnshippedWaybills::class)->unshippedSources(array_column($found, 'express_no'));
$packages = [];
foreach ($found as $shipment) $packages[$shipment['source_id']][] = $shipment;
foreach ($found as &$shipment) {
$shipment['unshipped'] = isset($unshipped[UnshippedWaybills::normalize($shipment['express_no'])]) ? $shipment['express_no'] : '';
if (preg_match('/^1\/([1-9]\d*)$/D', (string) $shipment['pkg_count'], $match) !== 1
|| count($packages[$shipment['source_id']]) !== (int) $match[1]) {
$shipment['valuation_error'] = '同步包裹商品明细尚未齐全,请核对';
}
}
unset($shipment);
return array_values($found);
}
public function readyMonths(): array
{
return $this->mirror->connection()->table(Shipping::MONTHS)->whereNotNull('active_generation')
->pluck('source_month')->map(static fn ($date) => substr($date, 0, 7))->all();
}
/** 缺发货文件时仍先核对共享未发出名单,不将未发出的订单转为按工单成本记账。 */
public function unshippedTracking(array $tracking): array
{
return array_keys(app(UnshippedWaybills::class)->unshippedSources($tracking));
}
/** @return array<string,?string> 规范化 SKU => 当前商品资料成本单价 */
public function costsFor(array $skus): array
{
if ($skus === []) return [];
$dataset = $this->datasets->get(ProductCatalogMirrorRepository::DATASET_KEY);
if (!$this->mirror->ready($dataset)) {
throw new RuntimeException('商品资料尚未完成首次同步');
}
$db = $this->mirror->connection();
$table = $dataset->targetTable();
$values = [];
foreach ($skus as $sku) {
$normalized = self::sku($sku);
foreach ([$normalized, mb_strtolower($normalized), str_replace('+', '_X002B_', $normalized)] as $value) {
if ($value !== '') $values[$value] = true;
}
}
$result = [];
$latest = [];
$exclusions = Schema::connection($db->getName())->hasTable('product_catalog_exclusions');
foreach (array_chunk(array_keys($values), 150) as $chunk) {
$query = $db->table($table)->where('sku_type', 'normal')->whereIn('sku_id', $chunk);
if ($exclusions) {
$query->whereNotExists(static function ($q) use ($table): void {
$q->selectRaw('1')->from('product_catalog_exclusions AS e')
->whereColumn('e.mirror_key', $table . '._mirror_key')
->whereRaw("e.sku_id_normalized = REPLACE(UPPER(TRIM({$table}.sku_id)), '_X002B_', '+')");
});
}
foreach ($query->orderByDesc('autoid')->get(['autoid', 'sku_id', 'cost_price']) as $record) {
$key = self::sku($record->sku_id);
if (!isset($latest[$key]) || (int) $record->autoid > $latest[$key]) {
$latest[$key] = (int) $record->autoid;
$result[$key] = $record->cost_price === null ? null : (string) $record->cost_price;
}
}
}
return $result;
}
/** 记账所在月份及前五个月,右端为下月1日(不含)。 */
public static function window(array $row): array
{
$month = Carbon::parse((string) $row['started_at'])->startOfMonth();
return [$month->copy()->subMonthsNoOverflow(5)->format('Y-m-d H:i:s'), $month->addMonth()->format('Y-m-d H:i:s')];
}
public static function missingMonth(array $row, array $readyMonths): ?string
{
[$from, $to] = self::window($row);
for ($month = Carbon::parse($from); $month->format('Y-m-d H:i:s') < $to; $month->addMonth()) {
if (!in_array($month->format('Y-m'), $readyMonths, true)) return $month->format('Y-m');
}
return null;
}
public static function numbers(mixed $value): array
{
return array_values(array_unique(array_filter(array_map(static fn ($v) => self::identifier($v), preg_split('/[\r\n,,、;;]+/u', (string) $value) ?: []), static fn ($v) => $v !== '')));
}
public static function sku(mixed $value): string
{
return str_replace('_X002B_', '+', mb_strtoupper(self::identifier($value)));
}
/** 只移除单号/商品编码外围的复制附加符,保留内部符号及前导0。 */
private static function identifier(mixed $value): string
{
return preg_replace('/^[\s\p{Cf}\'"‘’“”'"@@]+|[\s\p{Cf}\'"‘’“”'"@@]+$/u', '', (string) $value) ?? trim((string) $value);
}
}