快递账单对账支持附加费、补发扣款和运费差原因 (#1549)
This commit is contained in:
parent
77608ce497
commit
ca483879c9
65
app/Support/CourierBills/AccessoryDeductions.php
Normal file
65
app/Support/CourierBills/AccessoryDeductions.php
Normal file
@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use Modules\EcommerceFinance\View\AccessoryReshipPageData;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 「配件补发扣款」页算好的扣款,按首发快递(快递名称1)汇总,给对账单小汇总用。
|
||||
* 只取页面上「可扣款」的行(已选定首发快递、配了扣款比例、金额大于 0),和页面合计口径一致。
|
||||
*/
|
||||
class AccessoryDeductions
|
||||
{
|
||||
/** @var array<string,array<string,float>|null> 同一次请求里按月份缓存 */
|
||||
private array $cache = [];
|
||||
|
||||
/** @return array<string,float>|null 快递名称1 => 扣款金额(元);读不到时为 null */
|
||||
public function byCourier(string $month): ?array
|
||||
{
|
||||
if (! array_key_exists($month, $this->cache)) {
|
||||
$this->cache[$month] = $this->load($month);
|
||||
}
|
||||
|
||||
return $this->cache[$month];
|
||||
}
|
||||
|
||||
/** @param list<string> $expressNames */
|
||||
public function total(string $month, array $expressNames): ?float
|
||||
{
|
||||
$map = $this->byCourier($month);
|
||||
if ($map === null) {
|
||||
return null;
|
||||
}
|
||||
$sum = 0.0;
|
||||
foreach (array_unique($expressNames) as $name) {
|
||||
$sum += $map[$name] ?? 0.0;
|
||||
}
|
||||
|
||||
return round($sum, 2);
|
||||
}
|
||||
|
||||
/** @return array<string,float>|null */
|
||||
protected function load(string $month): ?array
|
||||
{
|
||||
try {
|
||||
$result = [];
|
||||
$page = app(AccessoryReshipPageData::class);
|
||||
foreach ($page->rows(['month' => $month, 'match_status' => 'ready']) as $row) {
|
||||
if (! AccessoryReshipPageData::inCategory($row, 'ready')) {
|
||||
continue;
|
||||
}
|
||||
$courier = trim((string) ($row['selected_courier'] ?? ($row['matches'][0]['courier'] ?? '')));
|
||||
if ($courier !== '') {
|
||||
$result[$courier] = ($result[$courier] ?? 0) + ((int) $row['deduction_cents']) / 100;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
} catch (Throwable $error) {
|
||||
report($error);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -16,6 +16,13 @@ final class BillParser
|
||||
public const AMOUNT_HEADERS = ['运费', '快递运费', '结算运费', '结算金额', '应付金额', '总运费', '金额', '费用'];
|
||||
public const WEIGHT_HEADERS = ['计费重量', '结算重量', '重量', '实际重量'];
|
||||
|
||||
/** 表名里出现这些字,整张表当附加费表,不读。(不含「上楼」二字本身:有的分组就叫「樵舍中通-上楼」。) */
|
||||
public const SURCHARGE_SHEET_WORDS = ['加收', '附加', '上楼费', '转件', '派送费', '派件费', '超区', '偏远', '退件', '退回', '赔付', '赔款', '理赔', '扣款', '罚款', '保价'];
|
||||
/** 金额列名里出现这些字,整张表当附加费表,不读。 */
|
||||
public const SURCHARGE_AMOUNT_WORDS = ['加收', '附加', '上楼', '转件', '派送', '派件', '超区', '偏远', '退件', '退回', '赔', '扣款', '罚款', '保价'];
|
||||
/** 有这一列时逐行看:费用项目不是运费的行(上楼费、转件费……)不读。 */
|
||||
public const ITEM_HEADERS = ['费用项目', '费用类型', '费用名称', '收费项目', '费用科目', '费用类别', '计费项目'];
|
||||
|
||||
private const HEADER_SCAN_ROWS = 15;
|
||||
private const SKIP_WORDS = ['合计', '总计', '小计', '汇总', '总额'];
|
||||
|
||||
@ -24,23 +31,49 @@ final class BillParser
|
||||
/**
|
||||
* @param array{waybill_header?:?string,amount_header?:?string,weight_header?:?string} $overrides
|
||||
* @return Generator<int, array{type:string}&array<string,mixed>>
|
||||
* type=sheet: {sheet, header_row, headers, waybill, amount, weight, skipped?:string}
|
||||
* type=sheet: {sheet, header_row, headers, waybill, amount, weight, item, skipped?:string, rows?:int}
|
||||
* type=surcharge_rows: {sheet, rows} 这张表里费用项目不是运费、没读进运费的行数
|
||||
* type=surcharge: {sheet, row, waybill, item, amount} 附加费(只记金额,不核对)
|
||||
* type=line: {sheet, row, waybill, amount, weight, raw}
|
||||
* type=reject: {sheet, row, value, reason}
|
||||
*/
|
||||
public function parse(string $path, string $extension, array $overrides = []): Generator
|
||||
{
|
||||
[$freight, $withWaybill] = $this->freightSheets($path, $extension, $overrides);
|
||||
[, $skip] = $this->freightSheets($path, $extension, $overrides);
|
||||
foreach ($this->reader->sheets($path, $extension) as $sheet => $rows) {
|
||||
if ($freight !== null && in_array((string) $sheet, $withWaybill, true) && ! in_array((string) $sheet, $freight, true)) {
|
||||
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'skipped' => '不是运费表(第一期只核运费),未读入'];
|
||||
if (isset($skip[(string) $sheet])) {
|
||||
[$reason, $headerRow, $waybillColumn, $amountColumn, $itemColumn, $amountHeader] = $skip[(string) $sheet];
|
||||
$count = 0;
|
||||
foreach ($rows as $rowNumber => $row) {
|
||||
if ($rowNumber <= $headerRow || trim((string) ($row[$waybillColumn] ?? '')) === '' || self::isTotalRow($row)) {
|
||||
continue;
|
||||
}
|
||||
$count++;
|
||||
// 附加费表:只取单号、费用项目、金额
|
||||
if ($amountColumn !== null) {
|
||||
$waybill = Waybill::parse(trim((string) $row[$waybillColumn]))['waybill'];
|
||||
$item = $itemColumn === null ? '' : trim((string) ($row[$itemColumn] ?? ''));
|
||||
if ($waybill !== null) {
|
||||
yield ['type' => 'surcharge', 'sheet' => (string) $sheet, 'row' => $rowNumber, 'waybill' => $waybill,
|
||||
'item' => $item !== '' ? $item : self::itemName($amountHeader, (string) $sheet),
|
||||
'amount' => self::number($row[$amountColumn] ?? null)];
|
||||
}
|
||||
}
|
||||
}
|
||||
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'skipped' => $reason, 'rows' => $count];
|
||||
continue;
|
||||
}
|
||||
$header = null;
|
||||
$columns = null;
|
||||
$scanned = 0;
|
||||
$surcharge = 0;
|
||||
$filled = 0;
|
||||
foreach ($rows as $rowNumber => $row) {
|
||||
if ($columns === null) {
|
||||
$filled += implode('', array_map(static fn ($v): string => trim((string) $v), $row)) === '' ? 0 : 1;
|
||||
if ($scanned >= self::HEADER_SCAN_ROWS) {
|
||||
continue;
|
||||
}
|
||||
$scanned++;
|
||||
$found = self::findColumns($row, $overrides);
|
||||
if ($found !== null) {
|
||||
@ -54,10 +87,6 @@ final class BillParser
|
||||
'headers' => array_map('strval', $row), ...$columns];
|
||||
continue;
|
||||
}
|
||||
if ($scanned >= self::HEADER_SCAN_ROWS) {
|
||||
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'skipped' => '前 15 行没有找到单号列,整表跳过'];
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -69,6 +98,19 @@ final class BillParser
|
||||
if ($trimmed === '' || self::isTotalRow($row) || preg_match('/^#(N\/A|REF!|VALUE!|DIV\/0!|NAME\?|NULL!|NUM!)$/i', $trimmed)) {
|
||||
continue;
|
||||
}
|
||||
// 运费和附加费混在一张表、用「费用项目」区分的:只读运费行。
|
||||
if ($columns['item'] !== null) {
|
||||
$item = preg_replace('/\s+/u', '', (string) ($row[$columns['item']] ?? '')) ?? '';
|
||||
if ($item !== '' && ! str_contains($item, '运费')) {
|
||||
$surcharge++;
|
||||
$waybill = Waybill::parse($trimmed)['waybill'];
|
||||
if ($waybill !== null) {
|
||||
yield ['type' => 'surcharge', 'sheet' => (string) $sheet, 'row' => $rowNumber, 'waybill' => $waybill,
|
||||
'item' => $item, 'amount' => $amount];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
$result = Waybill::parse($trimmed);
|
||||
if ($result['waybill'] === null) {
|
||||
yield ['type' => 'reject', 'sheet' => (string) $sheet, 'row' => $rowNumber, 'value' => $trimmed, 'reason' => $result['reason']];
|
||||
@ -81,31 +123,57 @@ final class BillParser
|
||||
yield ['type' => 'line', 'sheet' => (string) $sheet, 'row' => $rowNumber, 'waybill' => $result['waybill'],
|
||||
'amount' => $amount, 'weight' => $weight, 'raw' => $raw];
|
||||
}
|
||||
if ($columns === null && $scanned < self::HEADER_SCAN_ROWS) {
|
||||
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'skipped' => '没有找到单号列,整表跳过'];
|
||||
if ($surcharge > 0) {
|
||||
yield ['type' => 'surcharge_rows', 'sheet' => (string) $sheet, 'rows' => $surcharge];
|
||||
}
|
||||
if ($columns === null) {
|
||||
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'skipped' => ($scanned >= self::HEADER_SCAN_ROWS ? '前 15 行' : '')
|
||||
. '没有找到单号列,整表跳过', 'rows' => $filled];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 快递账单里常有好几张表:运费明细之外,还有附加费、上楼费、派件费用等明细(单号列、金额列都有)。
|
||||
* 第一期只核运费,所以只读金额列名带「运费」的表;一张都没有时(比如金额列就叫「金额」)才读所有带单号和金额的表。
|
||||
* 快递账单里常有好几张表:运费明细之外,还有附加费、上楼费、派件费用等明细(单号列、金额列都有)。第一期只核运费:
|
||||
* 1. 表名或金额列名像附加费的(加收、附加、上楼费、转件、派送、超区、偏远、退件、赔付、扣款……),整表不读;
|
||||
* 2. 剩下的表里,金额列名带「运费」的、或有「费用项目」列(逐行只读运费行)的,才当运费表读;
|
||||
* 3. 一张都没有时(比如金额列就叫「金额」),读剩下所有带单号和金额的表。
|
||||
*
|
||||
* @return array{0:list<string>|null,1:list<string>} [只读这些工作表(null = 不限), 找到单号列的工作表]
|
||||
* @return array{0:list<string>,1:array<string,array{0:string,1:int,2:int,3:?int,4:?int,5:string}>}
|
||||
* [运费表, 不读的表 => [原因, 表头行号, 单号列, 附加费金额列, 费用项目列, 金额列名]]
|
||||
*/
|
||||
public function freightSheets(string $path, string $extension, array $overrides = []): array
|
||||
{
|
||||
$freight = [];
|
||||
$withWaybill = [];
|
||||
$others = [];
|
||||
$skip = [];
|
||||
foreach ($this->reader->sheets($path, $extension) as $sheet => $rows) {
|
||||
$sheet = (string) $sheet;
|
||||
$scanned = 0;
|
||||
foreach ($rows as $row) {
|
||||
foreach ($rows as $rowNumber => $row) {
|
||||
$found = self::findColumns($row, $overrides);
|
||||
if ($found !== null) {
|
||||
$withWaybill[] = (string) $sheet;
|
||||
$amount = $found['amount'] === null ? '' : preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
|
||||
if (str_contains($amount, '运费') || (trim((string) ($overrides['amount_header'] ?? '')) !== '' && $found['amount'] !== null)) {
|
||||
$freight[] = (string) $sheet;
|
||||
$named = preg_replace('/\s+/u', '', $sheet) ?? '';
|
||||
if ($found['amount'] === null && self::containsAny($named, self::SURCHARGE_SHEET_WORDS)) {
|
||||
// 附加费表的金额列常直接叫「上楼费」「超长费」
|
||||
foreach ($row as $index => $cell) {
|
||||
$text = preg_replace('/\s+/u', '', (string) $cell) ?? '';
|
||||
if ($index !== $found['waybill'] && $text !== '' && (str_ends_with($text, '费') || str_contains($text, '金额'))) {
|
||||
$found['amount'] = (int) $index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($found['amount'] === null) {
|
||||
break;
|
||||
}
|
||||
$amount = preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
|
||||
if (self::containsAny($named, self::SURCHARGE_SHEET_WORDS) || self::containsAny($amount, self::SURCHARGE_AMOUNT_WORDS)) {
|
||||
$skip[$sheet] = ['附加费表:只读金额进小汇总,没有逐单核对', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount];
|
||||
} elseif (str_contains($amount, '运费') || $found['item'] !== null || trim((string) ($overrides['amount_header'] ?? '')) !== '') {
|
||||
$freight[] = $sheet;
|
||||
} else {
|
||||
$others[$sheet] = [(int) $rowNumber, $found['waybill']];
|
||||
}
|
||||
break;
|
||||
}
|
||||
@ -114,13 +182,39 @@ final class BillParser
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($freight === []) {
|
||||
$freight = array_keys($others);
|
||||
} else {
|
||||
foreach ($others as $sheet => [$headerRow, $waybill]) {
|
||||
$skip[$sheet] = ['不是运费表(第一期只核运费),未读入', $headerRow, $waybill, null, null, ''];
|
||||
}
|
||||
}
|
||||
|
||||
return [$freight === [] ? null : $freight, $withWaybill];
|
||||
return [$freight, $skip];
|
||||
}
|
||||
|
||||
/** 附加费表没有费用项目列时的项目名:金额列名像「退回运费」「上楼费」就用它,太笼统(费用金额、金额)就用表名。 */
|
||||
private static function itemName(string $amountHeader, string $sheet): string
|
||||
{
|
||||
$name = preg_replace('/(金额|(元)|\(元\))$/u', '', $amountHeader) ?? $amountHeader;
|
||||
|
||||
return in_array($name, ['', '费用', '应付', '结算', '合计', '总'], true) ? $sheet : $name;
|
||||
}
|
||||
|
||||
private static function containsAny(string $text, array $words): bool
|
||||
{
|
||||
foreach ($words as $word) {
|
||||
if (str_contains($text, $word)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int,string> $row
|
||||
* @return array{waybill:int,amount:?int,weight:?int}|null
|
||||
* @return array{waybill:int,amount:?int,weight:?int,item:?int}|null
|
||||
*/
|
||||
public static function findColumns(array $row, array $overrides = []): ?array
|
||||
{
|
||||
@ -131,8 +225,16 @@ final class BillParser
|
||||
}
|
||||
$amount = self::locate($headers, array_filter([$overrides['amount_header'] ?? null]) ?: self::AMOUNT_HEADERS, false);
|
||||
$weight = self::locate($headers, array_filter([$overrides['weight_header'] ?? null]) ?: self::WEIGHT_HEADERS, false);
|
||||
$item = null;
|
||||
foreach (self::ITEM_HEADERS as $candidate) {
|
||||
$index = array_search($candidate, $headers, true);
|
||||
if ($index !== false) {
|
||||
$item = (int) $index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return ['waybill' => $waybill, 'amount' => $amount, 'weight' => $weight];
|
||||
return ['waybill' => $waybill, 'amount' => $amount, 'weight' => $weight, 'item' => $item];
|
||||
}
|
||||
|
||||
/** 先按候选顺序全等匹配,再退到包含匹配(单号列不认「订单号」「交易单号」)。 */
|
||||
|
||||
@ -213,8 +213,9 @@ final class BillWorkbookReader
|
||||
try {
|
||||
$head = (string) fread($handle, 65536);
|
||||
rewind($handle);
|
||||
// 只看前 64KB;去掉末尾可能被截断的半个汉字再判断编码。
|
||||
$sample = strlen($head) === 65536 ? substr($head, 0, -4) : $head;
|
||||
// 只用前 64KB 中的完整行判断编码,避免从汉字中间截断。
|
||||
$lineEnd = strlen($head) === 65536 ? strrpos($head, "\n") : false;
|
||||
$sample = $lineEnd === false ? $head : substr($head, 0, $lineEnd + 1);
|
||||
$gbk = $sample !== '' && ! mb_check_encoding($sample, 'UTF-8');
|
||||
$line = 0;
|
||||
while (($row = fgetcsv($handle, 0, ',', '"', '')) !== false) {
|
||||
|
||||
@ -12,6 +12,8 @@ use RuntimeException;
|
||||
*/
|
||||
final class CourierBillMatcher
|
||||
{
|
||||
private ?AccessoryDeductions $deductions = null;
|
||||
|
||||
public function __construct(
|
||||
private readonly ShippingLookup $shipping,
|
||||
private readonly UnshippedWaybills $unshipped,
|
||||
@ -50,6 +52,11 @@ final class CourierBillMatcher
|
||||
$unshipped = $this->unshipped->unshippedSources($waybills);
|
||||
$unshipped = array_change_key_case($unshipped, CASE_UPPER);
|
||||
$shipping = $this->shipping->summaries($waybills);
|
||||
// 发货数据里查不到的单号,看是不是换单前的旧单号:旧面单没有发出去,归「未发出」,注明换成了哪个单号
|
||||
$missing = array_values(array_filter($waybills, static fn (string $w): bool => ! isset($shipping[$w]) && ! isset($unshipped[$w])));
|
||||
foreach ($missing === [] ? [] : $this->shipping->replacedBy($missing) as $old => [$new, $express]) {
|
||||
$unshipped[$old] = ['换单:已换成 ' . $new . ($express !== null ? '(' . $express . ')' : '')];
|
||||
}
|
||||
$nameSet = array_flip($names);
|
||||
|
||||
$seen = [];
|
||||
@ -69,7 +76,7 @@ final class CourierBillMatcher
|
||||
'express_name' => $ship['express_name'] ?? null,
|
||||
'calc_freight' => $ship['calc_freight'] ?? null,
|
||||
'charge_weight' => $ship['charge_weight'] ?? null,
|
||||
'unshipped_sources' => isset($unshipped[$key]) ? implode('、', $unshipped[$key]) : null,
|
||||
'unshipped_sources' => isset($unshipped[$key]) ? mb_substr(implode('、', $unshipped[$key]), 0, 128) : null,
|
||||
'self_amount' => self::selfAmount($category, $ship['calc_freight'] ?? null, $line->bill_amount, $line->resolution),
|
||||
];
|
||||
}
|
||||
@ -193,7 +200,9 @@ final class CourierBillMatcher
|
||||
->get();
|
||||
$items = [];
|
||||
$label = static fn (string $category, ?string $m): string => match ($category) {
|
||||
Category::MATCH, Category::DIFF, Category::UNCALCULATED => (int) substr($month, 5, 2) . '月运费',
|
||||
Category::MATCH => (int) substr($month, 5, 2) . '月运费',
|
||||
Category::DIFF => (int) substr($month, 5, 2) . '月运费-价格差',
|
||||
Category::UNCALCULATED => (int) substr($month, 5, 2) . '月运费-系统未核算',
|
||||
Category::PRIOR => (int) substr((string) $m, 5, 2) . '月运费(前月补提供)',
|
||||
Category::LATER => '跨月订单-' . (int) substr((string) $m, 5, 2) . '月,本月不结算',
|
||||
Category::DUPLICATE => '重复',
|
||||
@ -211,13 +220,42 @@ final class CourierBillMatcher
|
||||
$items[$name]['bill'] += (float) $row->bill;
|
||||
$items[$name]['self'] += (float) $row->self;
|
||||
}
|
||||
// 运费有差的再分原因:计费重量和账单重量不一样的算「重量差」,其余算「价格差」
|
||||
$weight = $db->table('courier_bill_lines')->where('statement_id', $statementId)->where('category', Category::DIFF)
|
||||
->whereNotNull('bill_weight')->whereNotNull('charge_weight')->whereRaw('ROUND(ABS(bill_weight - charge_weight), 4) > 0.005')
|
||||
->selectRaw('COUNT(*) as n, COALESCE(SUM(bill_amount),0) as bill, COALESCE(SUM(self_amount),0) as self')->first();
|
||||
$priceLabel = (int) substr($month, 5, 2) . '月运费-价格差';
|
||||
if ((int) $weight->n > 0 && isset($items[$priceLabel])) {
|
||||
$weightLabel = (int) substr($month, 5, 2) . '月运费-重量差';
|
||||
$items[$weightLabel] = ['bill' => (float) $weight->bill, 'self' => (float) $weight->self, 'sort' => $items[$priceLabel]['sort']];
|
||||
$items[$priceLabel]['bill'] -= (float) $weight->bill;
|
||||
$items[$priceLabel]['self'] -= (float) $weight->self;
|
||||
if ((int) $weight->n === (int) $db->table('courier_bill_lines')->where('statement_id', $statementId)->where('category', Category::DIFF)->count()) {
|
||||
unset($items[$priceLabel]);
|
||||
}
|
||||
}
|
||||
$m = (int) substr($month, 5, 2);
|
||||
foreach (['运费' => 100, '运费-重量差' => 101, '运费-价格差' => 102, '运费-系统未核算' => 103] as $suffix => $sort) {
|
||||
if (isset($items[$m . '月' . $suffix])) {
|
||||
$items[$m . '月' . $suffix]['sort'] = $sort;
|
||||
}
|
||||
}
|
||||
uasort($items, static fn (array $a, array $b): int => $a['sort'] <=> $b['sort']);
|
||||
|
||||
$this->addAccessoryDeduction($statementId, $month, $items);
|
||||
$manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
|
||||
->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip();
|
||||
$fees = $this->surchargeItems($statementId);
|
||||
$sort = 8000;
|
||||
foreach ($fees as $item => $sum) {
|
||||
if (! isset($manualLabels[$item]) && ! isset($items[$item])) {
|
||||
$items[$item] = ['bill' => $sum, 'self' => $sum, 'sort' => $sort++];
|
||||
}
|
||||
}
|
||||
$db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', false)->delete();
|
||||
$sort = 0;
|
||||
foreach ($items as $name => $item) {
|
||||
$db->table('courier_bill_summary_items')->insert([
|
||||
'statement_id' => $statementId, 'label' => $name, 'bill_amount' => round($item['bill'], 4),
|
||||
'statement_id' => $statementId, 'label' => $name, 'bill_amount' => $item['bill'] === null ? null : round($item['bill'], 4),
|
||||
'self_amount' => round($item['self'], 2), 'manual' => false, 'sort' => ++$sort,
|
||||
]);
|
||||
}
|
||||
@ -227,4 +265,90 @@ final class CourierBillMatcher
|
||||
'line_count' => (int) $totals->line_count, 'bill_amount' => round((float) $totals->bill, 2), 'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
/**
|
||||
* 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。
|
||||
* 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。
|
||||
*
|
||||
* @param array<string,array{bill:?float,self:float,sort:int}> $items
|
||||
*/
|
||||
private function addAccessoryDeduction(int $statementId, string $month, array &$items): void
|
||||
{
|
||||
$db = self::db();
|
||||
$manual = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
|
||||
->contains(static fn ($label): bool => SummaryMapper::classify((string) $label) === 'AL');
|
||||
if ($manual) {
|
||||
return;
|
||||
}
|
||||
$names = (array) json_decode((string) $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||||
->where('s.id', $statementId)->value('g.express_names'), true);
|
||||
$this->deductions ??= app(AccessoryDeductions::class);
|
||||
$total = $this->deductions->total($month, array_values(array_filter(array_map('trim', $names))));
|
||||
if ($total === null) {
|
||||
$existing = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)
|
||||
->where('manual', false)->where('label', '配件补发扣款')->value('self_amount');
|
||||
$total = -(float) $existing;
|
||||
}
|
||||
if ($total > 0) {
|
||||
$items['配件补发扣款'] = ['bill' => null, 'self' => -$total, 'sort' => 9000];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 这张对账单分到的附加费,按费用项目合计(快递开的金额,自算先按同额,不逐单核对)。
|
||||
* 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。
|
||||
*
|
||||
* @return array<string,float>
|
||||
*/
|
||||
private function surchargeItems(int $statementId): array
|
||||
{
|
||||
$db = self::db();
|
||||
$fileIds = $db->table('courier_bill_lines')->where('statement_id', $statementId)->distinct()->pluck('file_id')
|
||||
->merge($db->table('courier_bill_files')->where('statement_id', $statementId)->pluck('id'))
|
||||
->map(static fn ($id): int => (int) $id)->unique()->values()->all();
|
||||
if ($fileIds === []) {
|
||||
return [];
|
||||
}
|
||||
$result = [];
|
||||
$primaryIds = $db->table('courier_bill_files')->whereIn('id', $fileIds)->pluck('statement_id', 'id');
|
||||
foreach ($primaryIds as $fileId => $primaryId) {
|
||||
$primary = (int) $primaryId;
|
||||
$rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId);
|
||||
if (! (clone $rows)->exists()) {
|
||||
continue;
|
||||
}
|
||||
$shared = $db->table('courier_bill_lines')->where('file_id', $fileId)->distinct()->pluck('statement_id')
|
||||
->map(static fn ($id): int => (int) $id)->push($primary)->filter()->unique()->values()->all();
|
||||
$names = [];
|
||||
if (count($shared) > 1) {
|
||||
foreach ($db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||||
->whereIn('s.id', $shared)->orderBy('s.id')->get(['s.id', 'g.express_names']) as $statement) {
|
||||
foreach ((array) json_decode((string) $statement->express_names, true) as $name) {
|
||||
$names[trim((string) $name)] ??= (int) $statement->id;
|
||||
}
|
||||
}
|
||||
}
|
||||
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, &$result): void {
|
||||
$shipping = $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all());
|
||||
foreach ($chunk as $row) {
|
||||
$express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? '';
|
||||
if (($names[$express] ?? $primary) !== $statementId) {
|
||||
continue;
|
||||
}
|
||||
$item = preg_replace('/\s+/u', '', (string) $row->item) ?? '';
|
||||
$result[$item] = ($result[$item] ?? 0) + (float) $row->amount;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return array_map(static fn (float $v): float => round($v, 4), $result);
|
||||
}
|
||||
|
||||
/** 运费差异原因(导出「对账」用):重量差 / 价格差 / 系统未核算;一致的为 null。 */
|
||||
public static function diffReason(string $category, mixed $billWeight, mixed $chargeWeight): ?string
|
||||
{
|
||||
return match ($category) {
|
||||
Category::UNCALCULATED => '系统未核算',
|
||||
Category::DIFF => $billWeight !== null && $chargeWeight !== null && round(abs((float) $billWeight - (float) $chargeWeight), 4) > 0.005 ? '重量差' : '价格差',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -383,6 +383,7 @@ final class CourierBillStore
|
||||
}
|
||||
$db->transaction(function () use ($db, $file): void {
|
||||
$db->table('courier_bill_lines')->where('file_id', $file->id)->delete();
|
||||
$db->table('courier_bill_surcharges')->where('file_id', $file->id)->delete();
|
||||
$db->table('courier_bill_files')->where('id', $file->id)->delete();
|
||||
});
|
||||
Storage::disk(self::DISK)->delete($file->stored_path);
|
||||
@ -464,9 +465,13 @@ final class CourierBillStore
|
||||
$rows = 0;
|
||||
$amount = 0.0;
|
||||
$buffer = [];
|
||||
$surcharge = [];
|
||||
$fees = [];
|
||||
$feeTotal = 0.0;
|
||||
$feeCount = 0;
|
||||
$overlap = null;
|
||||
try {
|
||||
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap): string {
|
||||
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string {
|
||||
if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') {
|
||||
throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。');
|
||||
}
|
||||
@ -474,15 +479,34 @@ final class CourierBillStore
|
||||
if (! $reread) {
|
||||
$db->table('courier_bill_lines')->where('file_id', $fileId)->delete();
|
||||
}
|
||||
$db->table('courier_bill_surcharges')->where('file_id', $fileId)->delete();
|
||||
$overrides = ['waybill_header' => $group->waybill_header, 'amount_header' => $group->amount_header, 'weight_header' => $group->weight_header];
|
||||
foreach ($this->parser->parse($path, $extension, $overrides) as $item) {
|
||||
if ($item['type'] === 'sheet') {
|
||||
$sheets[] = isset($item['skipped'])
|
||||
? ['sheet' => $item['sheet'], 'skipped' => $item['skipped']]
|
||||
? ['sheet' => $item['sheet'], 'skipped' => $item['skipped'], 'rows' => $item['rows'] ?? null]
|
||||
: ['sheet' => $item['sheet'], 'header_row' => $item['header_row'], 'headers' => $item['headers'],
|
||||
'waybill' => $item['waybill'], 'amount' => $item['amount'], 'weight' => $item['weight']];
|
||||
continue;
|
||||
}
|
||||
if ($item['type'] === 'surcharge_rows') {
|
||||
$surcharge[$item['sheet']] = $item['rows'];
|
||||
continue;
|
||||
}
|
||||
if ($item['type'] === 'surcharge') {
|
||||
if ($item['amount'] === null) {
|
||||
continue;
|
||||
}
|
||||
$feeCount++;
|
||||
$feeTotal += (float) $item['amount'];
|
||||
$fees[] = ['file_id' => $fileId, 'sheet' => mb_substr($item['sheet'], 0, 100), 'row_no' => $item['row'],
|
||||
'waybill_no' => $item['waybill'], 'item' => mb_substr($item['item'], 0, 100), 'amount' => $item['amount']];
|
||||
if (count($fees) >= 500) {
|
||||
$db->table('courier_bill_surcharges')->insert($fees);
|
||||
$fees = [];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if ($item['type'] === 'reject') {
|
||||
$rejectedCount++;
|
||||
if (count($rejected) < 50) {
|
||||
@ -514,9 +538,17 @@ final class CourierBillStore
|
||||
$overlap = $this->overlap($fileId, (string) $file->bill_month, $reread);
|
||||
if ($overlap !== null && $overlap[1] * 2 >= $overlap[2]) {
|
||||
$db->table('courier_bill_lines')->where('file_id', $fileId)->delete();
|
||||
$db->table('courier_bill_surcharges')->where('file_id', $fileId)->delete();
|
||||
|
||||
return '';
|
||||
}
|
||||
if (! array_filter($sheets, static fn (array $s): bool => ! isset($s['skipped']))) {
|
||||
$db->table('courier_bill_surcharges')->where('file_id', $fileId)->delete();
|
||||
$feeCount = 0;
|
||||
$feeTotal = 0.0;
|
||||
} elseif ($fees !== []) {
|
||||
$db->table('courier_bill_surcharges')->insert($fees);
|
||||
}
|
||||
|
||||
return $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread);
|
||||
});
|
||||
@ -548,6 +580,22 @@ final class CourierBillStore
|
||||
if ($usable === []) {
|
||||
$notes[] = '没有找到含单号和运费列的工作表';
|
||||
}
|
||||
if ($feeCount > 0) {
|
||||
$notes[] = '附加费只读了金额进小汇总,没有逐单核对:' . $feeCount . ' 行,合计 ' . number_format($feeTotal, 2);
|
||||
}
|
||||
$unread = [];
|
||||
foreach ($sheets as $sheet) {
|
||||
if (isset($sheet['rows']) && $sheet['rows'] > 0 && ! str_starts_with($sheet['skipped'], '附加费')) {
|
||||
$why = str_contains($sheet['skipped'], '单号列') ? '没找到单号列' : '不是运费表';
|
||||
$unread[] = $sheet['sheet'] . '(' . $why . ',' . $sheet['rows'] . ' 行)';
|
||||
}
|
||||
}
|
||||
if ($unread !== []) {
|
||||
$notes[] = '没读入:' . implode('、', $unread);
|
||||
}
|
||||
foreach ($surcharge as $sheet => $count) {
|
||||
$notes[] = '「' . $sheet . '」里 ' . $count . ' 行费用项目不是运费,按附加费只读金额';
|
||||
}
|
||||
if ($split !== '') {
|
||||
$notes[] = $split;
|
||||
}
|
||||
@ -561,7 +609,7 @@ final class CourierBillStore
|
||||
'group_id' => $group->id, 'statement_id' => $statementId,
|
||||
'status' => $usable === [] ? 'failed' : 'parsed',
|
||||
'sheets' => json_encode($sheets, JSON_UNESCAPED_UNICODE),
|
||||
'row_count' => $rows, 'amount' => round($amount, 2), 'rejected_count' => $rejectedCount,
|
||||
'row_count' => $rows, 'amount' => round($amount + $feeTotal, 2), 'rejected_count' => $rejectedCount,
|
||||
'rejected_rows' => $rejected === [] ? null : json_encode($rejected, JSON_UNESCAPED_UNICODE),
|
||||
'message' => $notes === [] ? null : mb_substr(implode(';', $notes), 0, 255),
|
||||
'updated_at' => now(),
|
||||
@ -919,19 +967,36 @@ final class CourierBillStore
|
||||
/** 手工小汇总行(附加费、记账、补发配件、违约金、借支、车费……)。 */
|
||||
public function addSummaryItem(int $statementId, string $label, ?float $bill, ?float $self): void
|
||||
{
|
||||
$this->assertOpen($statementId);
|
||||
$sort = (int) $this->db()->table('courier_bill_summary_items')->where('statement_id', $statementId)->max('sort');
|
||||
$this->db()->table('courier_bill_summary_items')->insert([
|
||||
'statement_id' => $statementId, 'label' => mb_substr(trim($label), 0, 255), 'bill_amount' => $bill,
|
||||
'self_amount' => $self, 'manual' => true, 'sort' => max($sort, 1000) + 1,
|
||||
]);
|
||||
$db = $this->db();
|
||||
$db->transaction(function () use ($db, $statementId, $label, $bill, $self): void {
|
||||
$this->assertOpen($statementId);
|
||||
$items = $db->table('courier_bill_summary_items')->where('statement_id', $statementId);
|
||||
$sort = (int) (clone $items)->max('sort');
|
||||
$label = mb_substr(trim($label), 0, 255);
|
||||
$db->table('courier_bill_summary_items')->insert([
|
||||
'statement_id' => $statementId, 'label' => $label, 'bill_amount' => $bill,
|
||||
'self_amount' => $self, 'manual' => true, 'sort' => max($sort, 1000) + 1,
|
||||
]);
|
||||
$deduction = SummaryMapper::classify($label) === 'AL';
|
||||
$normalized = preg_replace('/\s+/u', '', $label) ?? '';
|
||||
$labels = $deduction ? [$normalized, '配件补发扣款'] : [$normalized];
|
||||
if ($items->where('manual', false)->whereIn('label', $labels)->exists()) {
|
||||
$this->matcher->refreshSummary($statementId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function deleteSummaryItem(int $statementId, int $itemId): void
|
||||
{
|
||||
$this->assertOpen($statementId);
|
||||
$this->db()->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('id', $itemId)
|
||||
->where('manual', true)->delete();
|
||||
$db = $this->db();
|
||||
$db->transaction(function () use ($db, $statementId, $itemId): void {
|
||||
$this->assertOpen($statementId);
|
||||
$removed = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('id', $itemId)
|
||||
->where('manual', true)->delete();
|
||||
if ($removed > 0) {
|
||||
$this->matcher->refreshSummary($statementId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1002,7 +1067,7 @@ final class CourierBillStore
|
||||
|
||||
private function assertOpen(int $statementId): void
|
||||
{
|
||||
if ($this->db()->table('courier_bill_statements')->where('id', $statementId)->value('status') !== 'open') {
|
||||
if ($this->db()->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') !== 'open') {
|
||||
throw new RuntimeException('对账单已确认结算,先撤销确认再修改。');
|
||||
}
|
||||
}
|
||||
|
||||
@ -242,6 +242,32 @@ final class ShippingLookup
|
||||
return $counts;
|
||||
}
|
||||
|
||||
/**
|
||||
* 换单:发货数据里「换单前单号」是这些单号的包裹(快递常按换单前的旧单号开账单)。
|
||||
*
|
||||
* @param list<string> $waybills
|
||||
* @return array<string,array{0:string,1:?string}> 旧单号(大写)=> [新快递单号, 新单号的快递名称1]
|
||||
*/
|
||||
public function replacedBy(array $waybills): array
|
||||
{
|
||||
$result = [];
|
||||
try {
|
||||
// front_no 没有索引,通常用一次查询覆盖一张账单的未匹配单号。
|
||||
foreach (array_chunk(array_values(array_unique($waybills)), 10000) as $chunk) {
|
||||
foreach ($this->connection()->table('jst_oms_shipping')->whereIn('front_no', $chunk)
|
||||
->whereNotNull('express_no')->where('express_no', '<>', '')
|
||||
->orderBy('id')->get(['front_no', 'express_no', 'express_name1']) as $row) {
|
||||
$old = strtoupper(trim((string) $row->front_no));
|
||||
$result[$old] ??= [strtoupper(trim((string) $row->express_no)), self::blank($row->express_name1)];
|
||||
}
|
||||
}
|
||||
} catch (\Illuminate\Database\QueryException $error) {
|
||||
report($error);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @return array<int,object> source_id => 核算结果 */
|
||||
private function freights(array $sourceIds): array
|
||||
{
|
||||
|
||||
@ -103,7 +103,7 @@ final class StatementExporter
|
||||
|
||||
[$sources, $original] = $this->originalHeaders($ids);
|
||||
$rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(self::FRONT, static fn ($f) => $f[0] !== '_')));
|
||||
$fullHeader = [...$original, ...array_keys(self::FRONT), ...array_values($rest), '处理结果', ...$tail];
|
||||
$fullHeader = [...$original, ...array_keys(self::FRONT), ...array_values($rest), '差异原因', '处理结果', ...$tail];
|
||||
|
||||
// 原始账单:底文件原封不动;第 2 个及以后的文件按值复制
|
||||
$originals = $this->writeOriginal($book, $files, $baseFileId);
|
||||
@ -132,6 +132,7 @@ final class StatementExporter
|
||||
foreach (array_keys($rest) as $field) {
|
||||
$cells[] = self::value($field, $ship[$field] ?? null);
|
||||
}
|
||||
$cells[] = CourierBillMatcher::diffReason((string) $line->category, $line->bill_weight, $line->charge_weight);
|
||||
$cells[] = Category::RESOLUTIONS[$line->resolution] ?? null;
|
||||
$book->row($name, [...$cells, ...$groupCell($line)]);
|
||||
}
|
||||
@ -236,7 +237,12 @@ final class StatementExporter
|
||||
$rows = [];
|
||||
foreach ($originals as [$name, $isRead, $reason, $lines, $isBase]) {
|
||||
$description = $isBase ? '快递原始账单,原文件原样(内容、格式、公式都没动)' : '快递原始账单(另一个文件,按值复制,格式没保留)';
|
||||
$rows[] = [$name, $description . ($isRead ? ';已核对运费。' : ';没有核对:' . preg_replace('/,?(整表跳过|未读入)$/u', '', (string) $reason) . '。'), $lines];
|
||||
$detail = match (true) {
|
||||
$isRead => '已核对运费。',
|
||||
str_starts_with((string) $reason, '附加费') => '附加费表,金额按费用项目进入小汇总。',
|
||||
default => '没有核对:' . preg_replace('/,?(整表跳过|未读入)$/u', '', (string) $reason) . '。',
|
||||
};
|
||||
$rows[] = [$name, $description . ';' . $detail, $lines];
|
||||
}
|
||||
$rows = [
|
||||
...$rows,
|
||||
|
||||
@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 快递账单里的附加费(上楼费、拦截费、超长费……):第一期不逐单核对,只把快递开的金额按单号存下来,
|
||||
* 按费用项目进对账单小汇总,让「快递提供金额」和账单总额一致。
|
||||
*/
|
||||
return new class extends Migration {
|
||||
public function up(): void
|
||||
{
|
||||
Schema::connection('business_mirror')->create('courier_bill_surcharges', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('file_id')->index();
|
||||
$table->string('sheet', 100);
|
||||
$table->unsignedInteger('row_no');
|
||||
$table->string('waybill_no', 96)->index();
|
||||
$table->string('item', 100)->comment('费用项目');
|
||||
$table->decimal('amount', 16, 4)->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::connection('business_mirror')->dropIfExists('courier_bill_surcharges');
|
||||
}
|
||||
};
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use App\Support\CourierBills\AccessoryDeductions;
|
||||
use App\Support\CourierBills\BillParser;
|
||||
use App\Support\CourierBills\BillWorkbookReader;
|
||||
use App\Support\CourierBills\Category;
|
||||
@ -133,6 +134,20 @@ final class CourierBillReconciliationTest extends FeatureTestCase
|
||||
$skipped = array_values(array_filter($items, fn ($i) => $i['type'] === 'sheet' && isset($i['skipped'])));
|
||||
$this->assertSame('加收&上楼费', $skipped[0]['sheet']);
|
||||
|
||||
// 金额列名带「运费」但像附加费的(退回运费),表名像附加费的,都整表不读;「费用项目」列逐行只读运费行
|
||||
$path = $this->workbook([
|
||||
'明细' => [['运单号', '费用项目', '费用金额'], ['ZT003', '运费', 9], ['ZT003', '上楼费', 6], ['ZT004', '', 4]],
|
||||
'退货' => [['运单号', '退回运费'], ['ZT005', 2.5]],
|
||||
'超区派送费' => [['运单号', '运费'], ['ZT006', 3]],
|
||||
]);
|
||||
$items = iterator_to_array(app(BillParser::class)->parse($path, 'xlsx'), false);
|
||||
$lines = array_values(array_filter($items, fn ($i) => $i['type'] === 'line'));
|
||||
$this->assertSame([['ZT003', 9.0], ['ZT004', 4.0]], array_map(fn ($l) => [$l['waybill'], $l['amount']], $lines));
|
||||
$this->assertSame([['type' => 'surcharge_rows', 'sheet' => '明细', 'rows' => 1]], array_values(array_filter($items, fn ($i) => $i['type'] === 'surcharge_rows')));
|
||||
$skipped = array_values(array_filter($items, fn ($i) => $i['type'] === 'sheet' && isset($i['skipped'])));
|
||||
$this->assertSame([['退货', 1], ['超区派送费', 1]], array_map(fn ($i) => [$i['sheet'], $i['rows']], $skipped));
|
||||
$this->assertStringStartsWith('附加费表', $skipped[0]['skipped']);
|
||||
|
||||
// 没有一张表的金额列叫「运费」时,照旧读所有带单号和金额的表
|
||||
$path = $this->workbook(['明细' => [['运单号', '金额'], ['ZT002', 8]]]);
|
||||
$lines = array_values(array_filter(iterator_to_array(app(BillParser::class)->parse($path, 'xlsx'), false), fn ($i) => $i['type'] === 'line'));
|
||||
@ -149,6 +164,25 @@ final class CourierBillReconciliationTest extends FeatureTestCase
|
||||
$this->assertSame(5.5, $lines[0]['amount']);
|
||||
}
|
||||
|
||||
public function test_large_utf8_csv_keeps_freight_and_surcharge_labels_at_the_encoding_sample_boundary(): void
|
||||
{
|
||||
$path = tempnam(sys_get_temp_dir(), 'bill_mixed_csv_');
|
||||
$this->temp[] = $path;
|
||||
$header = "运单号,运费,费用项目\n";
|
||||
$filler = "TEST001,5,运费\n";
|
||||
$beforeBoundary = $header . str_repeat($filler, 3600) . 'TEST002,3,';
|
||||
$spaces = str_repeat(' ', 65532 - strlen($beforeBoundary) - 1);
|
||||
file_put_contents($path, $beforeBoundary . $spaces . "上楼费\nTEST003,6,运费\n");
|
||||
|
||||
$amounts = [];
|
||||
foreach (app(BillParser::class)->parse($path, 'csv') as $row) {
|
||||
if (in_array($row['waybill'] ?? '', ['TEST002', 'TEST003'], true)) {
|
||||
$amounts[] = [$row['type'], $row['amount']];
|
||||
}
|
||||
}
|
||||
$this->assertSame([['surcharge', 3.0], ['line', 6.0]], $amounts);
|
||||
}
|
||||
|
||||
public function test_upload_classifies_lines_settles_and_flags_next_month_duplicates(): void
|
||||
{
|
||||
$this->seedShipping();
|
||||
@ -194,7 +228,9 @@ final class CourierBillReconciliationTest extends FeatureTestCase
|
||||
$summary = $store->db()->table('courier_bill_summary_items')->where('statement_id', $statementId)->orderBy('sort')
|
||||
->get()->map(fn ($i) => [$i->label, (float) $i->bill_amount, (float) $i->self_amount])->all();
|
||||
$this->assertSame([
|
||||
['10月运费', 26.0, 21.0],
|
||||
['10月运费', 10.0, 10.0],
|
||||
['10月运费-重量差', 12.0, 11.0],
|
||||
['10月运费-系统未核算', 4.0, 0.0],
|
||||
['9月运费(前月补提供)', 8.0, 6.0],
|
||||
['跨月订单-11月,本月不结算', 9.0, 0.0],
|
||||
['重复', 12.0, 0.0],
|
||||
@ -609,6 +645,118 @@ final class CourierBillReconciliationTest extends FeatureTestCase
|
||||
$this->assertSame([$ids[0]], $db->table('courier_bill_lines')->pluck('file_id')->map(fn ($id) => (int) $id)->all());
|
||||
}
|
||||
|
||||
public function test_accessory_reship_deductions_flow_into_the_summary(): void
|
||||
{
|
||||
$this->seedShipping();
|
||||
$this->app->instance(AccessoryDeductions::class, new class extends AccessoryDeductions {
|
||||
protected function load(string $month): ?array
|
||||
{
|
||||
return $month === '2026-10' ? ['河北中通-江三' => 12.5, '河北中通小件-江三' => 3.25, '别的快递' => 99.0] : [];
|
||||
}
|
||||
});
|
||||
$store = app(CourierBillStore::class);
|
||||
$store->saveGroup(null, ['name' => '河北中通-江三', 'express_names' => ['河北中通-江三', '河北中通小件-江三']]);
|
||||
$id = $store->upload([$this->upload('河北中通-江三10月.xlsx', [['运单号', '运费'], ['ZT001', 10]])], '2026-10', [], 'tester')[0];
|
||||
$statement = (int) $store->db()->table('courier_bill_files')->where('id', $id)->value('statement_id');
|
||||
$item = $store->db()->table('courier_bill_summary_items')->where('statement_id', $statement)->where('label', '配件补发扣款')->first();
|
||||
$this->assertNull($item->bill_amount);
|
||||
$this->assertSame(-15.75, (float) $item->self_amount);
|
||||
$this->assertSame(15.75, SummaryMapper::map(app(PayableSummary::class)->summaryItems([$statement]))['AL']);
|
||||
|
||||
// 已经手工加了配件补发扣款,就不再自动加
|
||||
$store->addSummaryItem($statement, '原单补发配件', null, -20);
|
||||
$this->assertSame(0, $store->db()->table('courier_bill_summary_items')->where('statement_id', $statement)->where('label', '配件补发扣款')->count());
|
||||
$manualId = (int) $store->db()->table('courier_bill_summary_items')->where('statement_id', $statement)->where('manual', true)->value('id');
|
||||
$store->deleteSummaryItem($statement, $manualId);
|
||||
$this->assertSame(15.75, SummaryMapper::map(app(PayableSummary::class)->summaryItems([$statement]))['AL']);
|
||||
}
|
||||
|
||||
public function test_export_keeps_every_original_sheet_and_upload_notes_unread_sheets(): void
|
||||
{
|
||||
$this->seedShipping();
|
||||
$store = app(CourierBillStore::class);
|
||||
$store->saveGroup(null, ['name' => '河北中通-江三', 'express_names' => ['河北中通-江三']]);
|
||||
$path = $this->workbook([
|
||||
'账单明细' => [['运单号', '运费'], ['ZT001', 10], ['ZT002', 11]],
|
||||
'退货数据' => [['南昌中通退货10.23', '', '退回运费'], ['ZT009', 'B9', 2.5]],
|
||||
'加收&上楼费' => [['运单号', '费用项目', '费用金额'], ['ZT001', '上楼费', 7], ['ZT002', '转件费', 3]],
|
||||
]);
|
||||
$id = $store->upload([new UploadedFile($path, '河北中通-江三10月.xlsx', null, null, true)], '2026-10', [], 'tester')[0];
|
||||
$file = $store->db()->table('courier_bill_files')->find($id);
|
||||
$this->assertSame(2, (int) $file->row_count);
|
||||
$this->assertSame('附加费只读了金额进小汇总,没有逐单核对:2 行,合计 10.00;没读入:退货数据(没找到单号列,2 行)', $file->message);
|
||||
// 附加费按费用项目进小汇总,快递金额 = 自算金额
|
||||
$fees = $store->db()->table('courier_bill_summary_items')->where('statement_id', $file->statement_id)->whereIn('label', ['上楼费', '转件费'])
|
||||
->orderBy('sort')->get()->map(fn ($i) => [$i->label, (float) $i->bill_amount, (float) $i->self_amount])->all();
|
||||
$this->assertSame([['上楼费', 7.0, 7.0], ['转件费', 3.0, 3.0]], $fees);
|
||||
$fees = $store->db()->table('courier_bill_summary_items')->where('statement_id', $file->statement_id)->where('label', '上楼费');
|
||||
$store->addSummaryItem((int) $file->statement_id, '上 楼费', 8, 8);
|
||||
$this->assertFalse((clone $fees)->where('manual', false)->exists());
|
||||
$manualId = (int) $store->db()->table('courier_bill_summary_items')->where('statement_id', $file->statement_id)->where('manual', true)->value('id');
|
||||
$store->deleteSummaryItem((int) $file->statement_id, $manualId);
|
||||
$this->assertSame(7.0, (float) $fees->value('bill_amount'));
|
||||
$duplicate = $store->upload([new UploadedFile($path, '河北中通-江三重复.xlsx', null, null, true)], '2026-10', [], 'tester')[0];
|
||||
$this->assertFalse($store->db()->table('courier_bill_surcharges')->where('file_id', $duplicate)->exists());
|
||||
$store->rematch((int) $file->statement_id);
|
||||
$this->assertSame(2, $store->db()->table('courier_bill_surcharges')->where('file_id', $id)->count());
|
||||
|
||||
$out = tempnam(sys_get_temp_dir(), 'cbx');
|
||||
$this->temp[] = $out;
|
||||
$handle = fopen($out, 'wb');
|
||||
app(StatementExporter::class)->export((int) $file->statement_id, $handle);
|
||||
fclose($handle);
|
||||
$book = IOFactory::createReader('Xlsx')->load($out);
|
||||
$this->assertSame(['账单明细', '退货数据', '加收&上楼费'], array_slice($book->getSheetNames(), 0, 3));
|
||||
$this->assertSame('南昌中通退货10.23', (string) $book->getSheetByName('退货数据')->getCell('A1')->getValue());
|
||||
$this->assertSame(3, $book->getSheetByName('加收&上楼费')->getHighestRow());
|
||||
$notes = $book->getSheetByName('说明')->toArray();
|
||||
$this->assertSame(['退货数据', '快递原始账单,原文件原样(内容、格式、公式都没动);没有核对:没有找到单号列。', 2], [$notes[2][0], $notes[2][1], (int) $notes[2][2]]);
|
||||
$book->disconnectWorksheets();
|
||||
}
|
||||
|
||||
public function test_old_waybill_of_a_replaced_label_counts_as_unshipped_and_price_diff_is_split(): void
|
||||
{
|
||||
$this->seedShipping();
|
||||
$ship = app(\App\Support\CourierBills\ShippingLookup::class)->connection();
|
||||
$ship->table('jst_oms_shipping')->insert(['express_no' => 'JDLD001', 'front_no' => 'OLD001', 'express_name1' => '河北中通-江三',
|
||||
'ship_time' => '2026-10-09 10:00:00', 'source_id' => 70]);
|
||||
$store = app(CourierBillStore::class);
|
||||
$store->saveGroup(null, ['name' => '河北中通-江三', 'express_names' => ['河北中通-江三']]);
|
||||
$id = $store->upload([$this->upload('河北中通-江三10月.xlsx', [['运单号', '重量', '运费'], ['OLD001', 1, 9], ['ZT002', 1, 12], ['ZT004', 1, 6]])], '2026-10', [], 'tester')[0];
|
||||
$statement = (int) $store->db()->table('courier_bill_files')->where('id', $id)->value('statement_id');
|
||||
$lines = $store->db()->table('courier_bill_lines')->where('statement_id', $statement)->orderBy('id')->get()->keyBy('waybill_no');
|
||||
$this->assertSame(Category::UNSHIPPED, $lines['OLD001']->category);
|
||||
$this->assertSame('换单:已换成 JDLD001(河北中通-江三)', $lines['OLD001']->unshipped_sources);
|
||||
$this->assertSame(Category::UNMATCHED, $lines['ZT004']->category);
|
||||
// 账单重量和计费重量一样、金额不一样:价格差
|
||||
$this->assertSame('价格差', CourierBillMatcher::diffReason($lines['ZT002']->category, $lines['ZT002']->bill_weight, $lines['ZT002']->charge_weight));
|
||||
$this->assertSame(['10月运费-价格差'], $store->db()->table('courier_bill_summary_items')->where('statement_id', $statement)
|
||||
->where('label', 'like', '10月运费%')->pluck('label')->all());
|
||||
}
|
||||
|
||||
public function test_surcharges_of_a_combined_bill_go_to_the_group_of_each_waybill(): void
|
||||
{
|
||||
$this->seedShipping();
|
||||
$store = app(CourierBillStore::class);
|
||||
$hebei = $store->saveGroup(null, ['name' => '河北中通-江三', 'express_names' => ['河北中通-江三'], 'bundle' => '江三+雅柏']);
|
||||
$bazhou = $store->saveGroup(null, ['name' => '霸州百世快运-雅柏', 'express_names' => ['霸州百世快运-雅柏'], 'bundle' => '江三+雅柏']);
|
||||
$path = $this->workbook([
|
||||
'账单明细' => [['运单号', '运费'], ['ZT001', 10], ['ZT005', 7]],
|
||||
'上楼费' => [['运单号', '上楼费'], ['ZT001', 20], ['ZT005', 30], ['ZT004', 5]],
|
||||
]);
|
||||
$id = $store->upload([new UploadedFile($path, '河北中通-江三10月.xlsx', null, null, true)], '2026-10', [], 'tester')[0];
|
||||
$statements = $store->db()->table('courier_bill_statements')->pluck('id', 'group_id');
|
||||
$fee = fn (int $group) => (float) $store->db()->table('courier_bill_summary_items')->where('statement_id', $statements[$group])
|
||||
->where('label', '上楼费')->value('bill_amount');
|
||||
// ZT001 属于江三,ZT005 属于雅柏;ZT004 查不到发货数据,归文件所属的江三
|
||||
$this->assertSame(25.0, $fee($hebei));
|
||||
$this->assertSame(30.0, $fee($bazhou));
|
||||
$this->assertSame(0, $store->db()->table('courier_bill_lines')->where('sheet', '上楼费')->count());
|
||||
|
||||
$store->deleteFile($id);
|
||||
$this->assertSame(0, $store->db()->table('courier_bill_surcharges')->count());
|
||||
}
|
||||
|
||||
public function test_month_express_names_counts_shipping_rows(): void
|
||||
{
|
||||
$this->seedShipping();
|
||||
@ -658,7 +806,7 @@ final class CourierBillReconciliationTest extends FeatureTestCase
|
||||
$files = $store->upload([new UploadedFile($path, 'first.xlsx', null, null, true), new UploadedFile($secondPath, 'second.xlsx', null, null, true)], '2026-10', [$group], 'tester');
|
||||
$id = (int) $store->db()->table('courier_bill_files')->where('id', $files[0])->value('statement_id');
|
||||
$this->assertSame(4, $store->db()->table('courier_bill_lines')->count());
|
||||
$this->assertEquals(60.824, $store->db()->table('courier_bill_summary_items')->where('statement_id', $id)->sum('bill_amount'));
|
||||
$this->assertEquals(258.824, $store->db()->table('courier_bill_summary_items')->where('statement_id', $id)->sum('bill_amount'));
|
||||
$output = tempnam(sys_get_temp_dir(), 'bill_precise_');
|
||||
$this->temp[] = $output;
|
||||
$handle = fopen($output, 'wb');
|
||||
@ -688,7 +836,7 @@ final class CourierBillReconciliationTest extends FeatureTestCase
|
||||
$this->assertSame('原始汇总', $book->getSheetByName('汇总')->getCell('A1')->getValue());
|
||||
$this->assertNotNull($book->getSheetByName('文件2-附加费'));
|
||||
$summary = $book->getSheetByName('汇总(系统)');
|
||||
$this->assertEquals(60.824, $summary->getCell('B' . $summary->getHighestDataRow())->getValue());
|
||||
$this->assertEquals(258.824, $summary->getCell('B' . $summary->getHighestDataRow())->getValue());
|
||||
$book->disconnectWorksheets();
|
||||
|
||||
$baseZip = new \ZipArchive();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user