293 lines
16 KiB
PHP
293 lines
16 KiB
PHP
<?php
|
||
|
||
namespace App\Support\DropshipFreight;
|
||
|
||
use App\Support\CourierBills\Category;
|
||
use App\Support\CourierBills\CourierBillMatcher;
|
||
use App\Support\CourierBills\ShippingLookup;
|
||
use App\Support\UnshippedWaybills;
|
||
|
||
/**
|
||
* 代发运费对账:某厂家某月,厂家账单的单号运费 对 系统按发货数据认出的代发包裹和核算运费。
|
||
*
|
||
* 分类和判断顺序与快递账单对账(自有快递)一致,见 CourierBillMatcher::categorize():
|
||
* 重复 → 未发出 → 匹配不到 → 快递不符 → 前月补提供 / 跨月订单 → 一致 / 一致但运费有差 / 一致(系统未核算);
|
||
* 系统认出是这家代发、厂家账单里没有的 = 厂家未提供。
|
||
*
|
||
* 代发的「快递不符」= 发货数据查得到,但不是这家代发单:不是从这家代发仓发的、快递名称1 不含关键字,或是自有快递。
|
||
* 发货数据按全部月份查,账单单号是上月发的就归「前月补提供」;哪个月都查不到才算「匹配不到」。
|
||
* 换单:账单开的旧单号在发货数据里查不到、但有包裹的换单前单号是它时,按实际发出的新单号判断(货实际发了):
|
||
* 新单号是这家代发单就照常分类、按我方核算结算,不是就归「快递不符」;新单号不再算「厂家未提供」。
|
||
* 结算:一致类和前月补提供按我方核算运费结算;其余不付(跨月订单留到发货那个月的账单;厂家未提供的不付)。
|
||
*/
|
||
final class DropshipReconciler
|
||
{
|
||
public const LABELS = [
|
||
Category::MATCH => '一致', Category::DIFF => '一致但运费有差', Category::UNCALCULATED => '一致(系统未核算)',
|
||
Category::PRIOR => '前月补提供', Category::LATER => '跨月订单', Category::DUPLICATE => '重复', Category::UNSHIPPED => '未发出',
|
||
Category::UNMATCHED => '匹配不到', Category::MISMATCH => '快递不符', Category::UNPROVIDED => '厂家未提供(不付)',
|
||
];
|
||
/** 按我方核算运费结算的分类。 */
|
||
public const PAYABLE = [Category::MATCH, Category::DIFF, Category::UNCALCULATED, Category::PRIOR];
|
||
/** 需要人工看一眼的分类。 */
|
||
public const ATTENTION = [Category::DIFF, Category::UNCALCULATED, Category::PRIOR, Category::LATER, Category::DUPLICATE,
|
||
Category::UNSHIPPED, Category::UNMATCHED, Category::MISMATCH];
|
||
|
||
private const CHUNK = 500;
|
||
|
||
public function __construct(
|
||
private readonly DropshipFreightStore $store,
|
||
private readonly ShippingLookup $shipping,
|
||
private readonly UnshippedWaybills $unshipped,
|
||
) {}
|
||
|
||
/**
|
||
* @return array{rows:list<array<string,mixed>>,summary:array<string,mixed>}
|
||
*/
|
||
public function factoryMonth(object $factory, string $month, ?array $own = null): array
|
||
{
|
||
$own = array_flip($own ?? $this->store->ownExpressNames());
|
||
$keywords = DropshipFreightStore::splitKeywords((string) $factory->keywords);
|
||
$bill = $this->store->db()->table('dropship_bill_lines')->where('factory_id', $factory->id)->where('bill_month', $month)
|
||
->get(['waybill_no', 'amount'])->groupBy('waybill_no')
|
||
->map(static fn ($rows): float => round((float) $rows->sum('amount'), 2))->all();
|
||
// 数字单号做数组键会变成整数,查库前转回字符串(整数和 varchar 比较会用不上索引)
|
||
$billed = array_map('strval', array_keys($bill));
|
||
$system = array_values(array_diff($this->dropshipWaybills($factory, $keywords, $own, $month), $billed));
|
||
$info = $this->shippingInfo([...$billed, ...$system]);
|
||
$unshipped = array_change_key_case($this->unshipped->unshippedSources($billed), CASE_UPPER);
|
||
// 换单:账单开的是旧单号、发货数据里是新单号。货实际发了,运费看新单号是不是这家代发单(代发仓 + 关键字 + 非自有快递)
|
||
$missing = array_values(array_filter($billed, static fn (string $w): bool => ! isset($info[$w])));
|
||
$replaced = $missing === [] ? [] : $this->shipping->replacedBy($missing);
|
||
$newInfo = $this->shippingInfo(array_values(array_diff(array_map(static fn (array $r): string => $r[0], $replaced), array_keys($info))));
|
||
// 同一个包裹的所有单号(换单前后):以前月份的账单开过其中任何一个,都算重复,免得旧单号、新单号各付一次
|
||
$aliases = [];
|
||
foreach ($billed as $waybill) {
|
||
$aliases[$waybill] = array_values(array_unique(array_filter([...($info[$waybill]['fronts'] ?? []),
|
||
$replaced[$waybill][0] ?? null, ...($info[$replaced[$waybill][0] ?? '']['fronts'] ?? [])],
|
||
static fn ($w): bool => $w !== null && $w !== '' && $w !== $waybill)));
|
||
}
|
||
$earliest = $this->earlierBills((int) $factory->id, $month, array_values(array_unique([...$billed, ...array_merge(...array_values($aliases ?: [[]]))])));
|
||
$earlier = [];
|
||
foreach ($billed as $waybill) {
|
||
$months = array_values(array_filter(array_map(static fn (string $w): ?string => $earliest[$w] ?? null, [$waybill, ...$aliases[$waybill]])));
|
||
if ($months !== []) {
|
||
$earlier[$waybill] = min($months);
|
||
}
|
||
}
|
||
$billedSet = array_flip($billed);
|
||
$isDropship = static fn (array $i): bool => $i['warehouse'] === $factory->warehouse && $i['express'] !== null
|
||
&& ! isset($own[$i['express']]) && self::matches($i['express'], $keywords);
|
||
|
||
$rows = [];
|
||
$covered = [];
|
||
foreach ($billed as $waybill) {
|
||
$i = $info[$waybill] ?? null;
|
||
$swap = null;
|
||
if ($i === null && isset($replaced[$waybill])) {
|
||
$swap = $replaced[$waybill][0];
|
||
$i = $info[$swap] ?? $newInfo[$swap] ?? null;
|
||
$covered[$swap] = true;
|
||
}
|
||
$ship = $i === null ? null : ['ship_time' => $i['ship_time'], 'express_name' => $i['express'], 'calc_freight' => $i['calc']];
|
||
// 是这家代发单就让「快递不符」那一步通过,不是就不通过
|
||
$names = $i !== null && $isDropship($i) ? [(string) $i['express'] => 0] : [];
|
||
$duplicateMonth = $earlier[$waybill] ?? ($swap !== null && isset($billedSet[$swap]) ? $month : null);
|
||
[$category, $categoryMonth] = CourierBillMatcher::categorize(false, $duplicateMonth,
|
||
$swap === null && isset($unshipped[$waybill]), $ship, $names, $month, $bill[$waybill]);
|
||
$note = match ($category) {
|
||
Category::DUPLICATE => $swap !== null && $duplicateMonth === $month ? '换单后的新单号 ' . $swap . ' 账单里也开了,只算新单号'
|
||
: $categoryMonth . ' 的账单已开过这个包裹' . ($aliases[$waybill] !== [] ? '(换单前后单号:' . implode('、', $aliases[$waybill]) . ')' : ''),
|
||
Category::UNSHIPPED => implode('、', $unshipped[$waybill]),
|
||
Category::UNMATCHED => '发货数据里哪个月都查不到这个单号',
|
||
Category::MISMATCH => isset($own[(string) $i['express']]) ? '自有快递「' . $i['express'] . '」,不给代发仓结算运费'
|
||
: '发货数据:' . ($i['warehouse'] ?: '无仓库') . ' / ' . ($i['express'] ?: '无快递名称1'),
|
||
Category::PRIOR, Category::LATER => $categoryMonth . ' 发货',
|
||
Category::UNCALCULATED => $i['calc_status'],
|
||
default => null,
|
||
};
|
||
if ($swap !== null && $category !== Category::DUPLICATE) {
|
||
$note = '换单:实际发出 ' . $swap . '(' . ($i['express'] ?? '无快递名称1') . ')' . ($note !== null ? ';' . $note : '')
|
||
. ($i === null ? ';新单号发货数据里也查不到' : '');
|
||
}
|
||
$rows[] = self::row($waybill, $i, $bill[$waybill], $category, $categoryMonth, $note);
|
||
}
|
||
$system = array_values(array_filter($system, static fn (string $w): bool => ! isset($covered[$w])));
|
||
foreach ($system as $waybill) {
|
||
$rows[] = self::row($waybill, $info[$waybill] ?? null, null, Category::UNPROVIDED, null, '厂家账单里没有,不付');
|
||
}
|
||
$order = array_flip(array_keys(self::LABELS));
|
||
usort($rows, static fn (array $a, array $b): int => [$order[$a['status']], (string) $a['ship_time']] <=> [$order[$b['status']], (string) $b['ship_time']]);
|
||
|
||
return ['rows' => $rows, 'summary' => self::summarize($factory, $month, $rows)];
|
||
}
|
||
|
||
public static function label(string $status, ?string $month = null): string
|
||
{
|
||
return in_array($status, [Category::PRIOR, Category::LATER], true) && $month !== null
|
||
? Category::label($status, $month) : (self::LABELS[$status] ?? $status);
|
||
}
|
||
|
||
private static function row(string $waybill, ?array $i, ?float $billed, string $status, ?string $statusMonth, ?string $note): array
|
||
{
|
||
$calc = $i['calc'] ?? null;
|
||
|
||
return ['waybill' => $waybill, 'ship_time' => $i['ship_time'] ?? null, 'express' => $i['express'] ?? null,
|
||
'warehouse' => $i['warehouse'] ?? null, 'bill' => $billed, 'calc' => $calc,
|
||
'settle' => in_array($status, self::PAYABLE, true) ? $calc : null,
|
||
'diff' => $billed !== null && $calc !== null ? round($billed - $calc, 2) : null,
|
||
'status' => $status, 'status_month' => $statusMonth, 'label' => self::label($status, $statusMonth),
|
||
'note' => $note, 'formula' => $i['formula'] ?? null];
|
||
}
|
||
|
||
/** @param list<array<string,mixed>> $rows */
|
||
public static function summarize(object $factory, string $month, array $rows): array
|
||
{
|
||
$counts = array_fill_keys(array_keys(self::LABELS), 0);
|
||
$bill = $settle = 0.0;
|
||
$billedCount = $over = $under = 0;
|
||
foreach ($rows as $row) {
|
||
$counts[$row['status']]++;
|
||
if ($row['bill'] !== null) {
|
||
$billedCount++;
|
||
$bill += $row['bill'];
|
||
}
|
||
$settle += (float) $row['settle'];
|
||
if ($row['status'] === Category::DIFF) {
|
||
$row['diff'] > 0 ? $over++ : $under++;
|
||
}
|
||
}
|
||
|
||
return ['factory_id' => (int) $factory->id, 'factory' => $factory->name, 'warehouse' => $factory->warehouse, 'month' => $month,
|
||
'keywords' => $factory->keywords, 'billed' => $billedCount, 'bill' => round($bill, 2), 'settle' => round($settle, 2),
|
||
'diff' => round($bill - $settle, 2), 'counts' => $counts, 'over' => $over, 'under' => $under,
|
||
'attention' => array_sum(array_intersect_key($counts, array_flip(self::ATTENTION)))];
|
||
}
|
||
|
||
public static function matches(string $express, array $keywords): bool
|
||
{
|
||
foreach ($keywords as $keyword) {
|
||
if ($keyword !== '' && str_contains($express, $keyword)) {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
/** 系统认出的这家本月代发单号:代发仓发出、快递名称1 含关键字、不是自有快递。 @return list<string> */
|
||
private function dropshipWaybills(object $factory, array $keywords, array $own, string $month): array
|
||
{
|
||
if ($keywords === []) {
|
||
return [];
|
||
}
|
||
[$from, $to] = DropshipFreightStore::monthRange($month);
|
||
$rows = $this->shipping->connection()->table('jst_oms_shipping')->where('warehouse_name', $factory->warehouse)
|
||
->where('ship_time', '>=', $from)->where('ship_time', '<', $to)
|
||
->where(function ($query) use ($keywords): void {
|
||
foreach ($keywords as $keyword) {
|
||
$query->orWhere('express_name1', 'like', '%' . $keyword . '%');
|
||
}
|
||
})
|
||
->distinct()->get(['express_no', 'express_name1']);
|
||
$result = [];
|
||
foreach ($rows as $row) {
|
||
$express = trim((string) $row->express_name1);
|
||
$waybill = strtoupper(trim((string) $row->express_no));
|
||
if ($waybill !== '' && ! isset($own[$express])) {
|
||
$result[$waybill] = true;
|
||
}
|
||
}
|
||
|
||
return array_map('strval', array_keys($result));
|
||
}
|
||
|
||
/**
|
||
* 单号的发货信息和核算运费(一个单号几个包裹时运费相加,任一包裹没核算成功就算未核算)。
|
||
*
|
||
* @param list<string> $waybills
|
||
* @return array<string,array{ship_time:?string,month:?string,express:?string,warehouse:?string,calc:?float,calc_status:?string,formula:?string}>
|
||
*/
|
||
private function shippingInfo(array $waybills): array
|
||
{
|
||
$result = [];
|
||
$connection = $this->shipping->connection();
|
||
foreach (array_chunk($waybills, self::CHUNK) as $chunk) {
|
||
$rows = $connection->table('jst_oms_shipping')->whereIn('express_no', $chunk)->orderBy('id')
|
||
->get(['express_no', 'express_name1', 'warehouse_name', 'ship_time', 'source_id', 'front_no']);
|
||
$sources = [];
|
||
foreach ($rows as $row) {
|
||
$key = strtoupper(trim((string) $row->express_no));
|
||
$item = $result[$key] ?? ['ship_time' => null, 'month' => null, 'express' => null, 'warehouse' => null,
|
||
'calc' => null, 'calc_status' => null, 'formula' => null, 'fronts' => []];
|
||
if ($row->ship_time !== null && ($item['ship_time'] === null || (string) $row->ship_time < $item['ship_time'])) {
|
||
$item['ship_time'] = (string) $row->ship_time;
|
||
$item['month'] = substr((string) $row->ship_time, 0, 7);
|
||
}
|
||
$item['express'] ??= self::blank($row->express_name1);
|
||
$item['warehouse'] ??= self::blank($row->warehouse_name);
|
||
$front = strtoupper(trim((string) ($row->front_no ?? '')));
|
||
if ($front !== '' && $front !== $key && ! in_array($front, $item['fronts'], true)) {
|
||
$item['fronts'][] = $front;
|
||
}
|
||
if ($row->source_id !== null) {
|
||
$sources[$key][(int) $row->source_id] = true;
|
||
}
|
||
$result[$key] = $item;
|
||
}
|
||
$ids = array_merge(...array_values(array_map('array_keys', $sources ?: [[]])));
|
||
$freights = [];
|
||
foreach (array_chunk(array_values(array_unique($ids)), self::CHUNK) as $part) {
|
||
foreach ($connection->table('jst_oms_shipping_freight')->whereIn('source_id', $part)->get() as $row) {
|
||
$freights[(int) $row->source_id] = $row;
|
||
}
|
||
}
|
||
foreach ($sources as $key => $set) {
|
||
$total = 0.0;
|
||
$ok = true;
|
||
$status = null;
|
||
$formulas = [];
|
||
foreach (array_keys($set) as $source) {
|
||
$freight = $freights[$source] ?? null;
|
||
if ($freight === null || strtoupper((string) $freight->status) !== 'OK' || $freight->freight === null) {
|
||
$ok = false;
|
||
$status = $freight === null ? '还没核算(等运费核算跑完)' : (string) ($freight->status ?: '没核算出运费');
|
||
break;
|
||
}
|
||
$total += (float) $freight->freight;
|
||
if (($freight->formula ?? null) !== null && $freight->formula !== '') {
|
||
$formulas[] = (string) $freight->formula;
|
||
}
|
||
}
|
||
$result[$key]['calc'] = $ok ? round($total, 2) : null;
|
||
$result[$key]['calc_status'] = $ok ? null : $status;
|
||
$result[$key]['formula'] = $formulas === [] ? null : implode(';', $formulas);
|
||
}
|
||
}
|
||
|
||
return $result;
|
||
}
|
||
|
||
/** @return array<string,string> 单号 => 以前最早哪个月的账单开过 */
|
||
private function earlierBills(int $factoryId, string $month, array $waybills): array
|
||
{
|
||
$result = [];
|
||
foreach (array_chunk($waybills, self::CHUNK) as $chunk) {
|
||
foreach ($this->store->db()->table('dropship_bill_lines')->where('factory_id', $factoryId)->where('bill_month', '<', $month)
|
||
->whereIn('waybill_no', $chunk)->distinct()->get(['waybill_no', 'bill_month']) as $row) {
|
||
$key = (string) $row->waybill_no;
|
||
$result[$key] = isset($result[$key]) ? min($result[$key], (string) $row->bill_month) : (string) $row->bill_month;
|
||
}
|
||
}
|
||
|
||
return $result;
|
||
}
|
||
|
||
private static function blank(mixed $value): ?string
|
||
{
|
||
$value = trim((string) $value);
|
||
|
||
return $value === '' ? null : $value;
|
||
}
|
||
}
|