CaiWuXiTong/app/Support/CourierBills/PayableSummary.php

345 lines
16 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 App\Support\CourierBills;
use Illuminate\Database\ConnectionInterface;
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
use RuntimeException;
use Throwable;
/**
* 快递应付汇总:格式同财务手工「快递汇总表」(汇总 sheet,A–AW 列)。
*
* 每月一套承运商行,所有承运商常驻(停运、旧账也一直挂着)。存的是手工/导入的单元格;
* 有对账单的承运商,金额列在读取时由小汇总归集(SummaryMapper)覆盖,不落库,
* 所以对账单改了、确认了,汇总随时是最新的。
*/
final class PayableSummary
{
/** 列字母 => 表头(与手工表第 2、3 行一致)。 */
public const COLUMNS = [
'A' => '合同开始时间', 'B' => '合同截止时间', 'C' => '签订公司', 'D' => '负责人', 'E' => '承运状态', 'F' => '序号',
'G' => '快递公司主体名称', 'H' => '承运商', 'I' => '月初结余', 'J' => '补给快递', 'K' => '快递提供金额',
'L' => '对账差异金额', 'M' => '核对确定金额', 'N' => '面单', 'O' => '借支', 'P' => '赔付金额', 'Q' => '其他补款',
'R' => '本月应付金额', 'S' => '本次实付金额', 'T' => '对公打款金额', 'U' => '对私打款金额', 'V' => '快递负责人',
'W' => '备注', 'X' => '备注1', 'Y' => '是否确认', 'Z' => 'e签宝签字单/纸质签字单', 'AA' => '电子签章经办人',
'AB' => '签字单到达日期', 'AC' => '收据', 'AD' => '是否打款', 'AE' => '合同',
...SummaryMapper::DIFF_COLUMNS,
'AS' => '记账补款金额', 'AT' => '补充说明', 'AU' => '仓库', 'AV' => '更改原因', 'AW' => '备注',
];
/** 金额列。 */
public const MONEY = ['I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS'];
/** 页面上可直接改的列(其余来自导入、快递资料或对账单)。 */
public const EDITABLE = ['D' => '负责人', 'E' => '承运状态', 'I' => '月初结余', 'Q' => '其他补款', 'S' => '本次实付金额', 'W' => '备注', 'AU' => '仓库'];
/** 有对账单时由小汇总覆盖的列。 */
private const FROM_STATEMENTS = ['J', 'K', 'L', 'N', 'O', 'P', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT'];
public function __construct(private readonly CourierInformationMirrorRepository $couriers) {}
public function db(): ConnectionInterface
{
return CourierBillMatcher::db();
}
/** @return list<string> 已有汇总的月份(新到旧) */
public function months(): array
{
return $this->db()->table('courier_payable_summary_rows')->distinct()->orderByDesc('month')->pluck('month')->all();
}
/**
* 当月汇总行(已叠加快递资料和对账单)。
*
* @return list<array{id:int,cells:array<string,mixed>,status:string,statements:list<array{id:int,group:string,status:string}>,check:?array{K:float,M:float,diff:float},expired:bool}>
*/
public function rows(string $month): array
{
$stored = $this->db()->table('courier_payable_summary_rows')->where('month', $month)->orderBy('sort')->get();
$statements = $this->statementsByCarrier($month);
try {
$contracts = $this->couriers->contractsByName($stored->pluck('carrier')->all());
} catch (Throwable $error) {
report($error);
$contracts = [];
}
$today = now()->toDateString();
$rows = [];
foreach ($stored as $row) {
$cells = (array) json_decode((string) $row->cells, true);
$contract = $contracts[$row->carrier] ?? null;
if ($contract !== null) {
$cells['A'] = $contract['contract_start'] ?? ($cells['A'] ?? null);
$cells['B'] = $contract['contract_end'] ?? ($cells['B'] ?? null);
$cells['C'] = $contract['company'] !== '' ? $contract['company'] : ($cells['C'] ?? null);
$cells['G'] = $contract['body'] !== '' ? $contract['body'] : ($cells['G'] ?? null);
}
$mine = $statements[$row->carrier] ?? [];
// 导入的汇总里已经有金额(手工做完的月份):以导入为准,对账单算出来的只用来比对;
// 新建的月份金额是空的,才用对账单的小汇总填。
$imported = collect(self::FROM_STATEMENTS)->contains(static fn (string $key): bool => abs((float) ($cells[$key] ?? 0)) > 0.004);
$check = null;
if ($mine !== []) {
$mapped = SummaryMapper::map($this->summaryItems(array_column($mine, 'id')));
if ($imported) {
$check = ['K' => round((float) $mapped['K'], 2), 'M' => round((float) $mapped['K'] - (float) $mapped['L'], 2),
'diff' => round((float) ($cells['K'] ?? 0) - (float) ($cells['L'] ?? 0) - (float) $mapped['K'] + (float) $mapped['L'], 2)];
} else {
foreach (self::FROM_STATEMENTS as $key) {
$cells[$key] = $mapped[$key];
}
}
}
foreach (self::MONEY as $key) {
if (isset($cells[$key]) && is_numeric($cells[$key])) {
$cells[$key] = (float) $cells[$key];
}
}
$cells = SummaryMapper::totals($cells);
$hasBill = abs((float) ($cells['K'] ?? 0)) > 0.004;
$status = match (true) {
$mine !== [] && ! $imported => collect($mine)->every(static fn (array $s): bool => $s['status'] === 'confirmed') ? '已确认' : '待处理',
$hasBill => (string) ($cells['Y'] ?? '') === '已确认' ? '已确认' : '待处理',
abs((float) ($cells['I'] ?? 0)) > 0.004 => '旧账挂账',
default => '本月无账单',
};
$end = self::date($cells['B'] ?? null);
$rows[] = [
'id' => (int) $row->id, 'cells' => $cells, 'status' => $status, 'statements' => $mine, 'check' => $check,
'expired' => $end !== null && $end < $today,
];
}
return $rows;
}
/** @return array<string,list<array{id:int,group:string,status:string}>> 承运商 => 对账单 */
private function statementsByCarrier(string $month): array
{
$result = [];
$rows = $this->db()->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
->where('s.bill_month', $month)->where('s.line_count', '>', 0)
->get(['s.id', 's.status', 'g.name', 'g.summary_carrier']);
foreach ($rows as $row) {
$carrier = trim((string) ($row->summary_carrier ?: $row->name));
$result[$carrier][] = ['id' => (int) $row->id, 'group' => (string) $row->name, 'status' => (string) $row->status];
}
return $result;
}
/** @return list<array{label:string,bill:?float,self:?float}> */
public function summaryItems(array $statementIds): array
{
return $this->db()->table('courier_bill_summary_items')->whereIn('statement_id', $statementIds)
->orderBy('statement_id')->orderBy('sort')->get()
->map(static fn ($item): array => ['label' => (string) $item->label,
'bill' => $item->bill_amount === null ? null : (float) $item->bill_amount,
'self' => $item->self_amount === null ? null : (float) $item->self_amount])
->all();
}
/**
* 生成新月份:从最近一个月复制全部承运商,月初结余 = 上月本月应付 − 上月本次实付(未付按 0 算),
* 其余金额和本月签字/打款信息清空。
*/
public function createMonth(string $month): int
{
if ($this->db()->table('courier_payable_summary_rows')->where('month', $month)->exists()) {
throw new RuntimeException($month . ' 已经有汇总。');
}
$previous = $this->db()->table('courier_payable_summary_rows')->where('month', '<', $month)->max('month');
if ($previous === null) {
throw new RuntimeException('还没有任何月份的汇总,请先导入一个月的手工快递汇总表。');
}
$keep = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'V', 'AA', 'AE', 'AU'];
$count = 0;
$this->db()->transaction(function () use ($previous, $month, $keep, &$count): void {
foreach ($this->rows($previous) as $index => $row) {
$cells = array_intersect_key($row['cells'], array_flip($keep));
$cells['I'] = round((float) ($row['cells']['R'] ?? 0) - (float) ($row['cells']['S'] ?? 0), 2);
$this->db()->table('courier_payable_summary_rows')->insert([
'month' => $month, 'sort' => $index + 1, 'carrier' => (string) ($row['cells']['H'] ?? ''),
'cells' => json_encode($cells, JSON_UNESCAPED_UNICODE), 'created_at' => now(), 'updated_at' => now(),
]);
$count++;
}
});
return $count;
}
/** 手工改一个单元格(只允许 EDITABLE 列)。 */
public function updateCell(int $rowId, string $column, ?string $value): void
{
if (! isset(self::EDITABLE[$column])) {
throw new RuntimeException('这一列不能手工修改。');
}
$row = $this->db()->table('courier_payable_summary_rows')->find($rowId);
if ($row === null) {
throw new RuntimeException('汇总行不存在。');
}
$cells = (array) json_decode((string) $row->cells, true);
if (in_array($column, self::MONEY, true)) {
$number = BillParser::number($value);
if ($value !== null && trim($value) !== '' && $number === null) {
throw new RuntimeException(self::COLUMNS[$column] . '须为数字。');
}
$cells[$column] = $number;
} else {
$cells[$column] = $value === null ? null : mb_substr(trim($value), 0, 500);
}
$this->db()->table('courier_payable_summary_rows')->where('id', $rowId)->update([
'cells' => json_encode($cells, JSON_UNESCAPED_UNICODE), 'updated_at' => now(),
]);
}
/** 新增一个承运商(排在最后)。 */
public function addCarrier(string $month, string $carrier): void
{
$carrier = trim($carrier);
if ($carrier === '' || $this->db()->table('courier_payable_summary_rows')->where('month', $month)->where('carrier', $carrier)->exists()) {
throw new RuntimeException('承运商为空或已存在。');
}
$sort = (int) $this->db()->table('courier_payable_summary_rows')->where('month', $month)->max('sort') + 1;
$this->db()->table('courier_payable_summary_rows')->insert([
'month' => $month, 'sort' => $sort, 'carrier' => $carrier,
'cells' => json_encode(['F' => $sort, 'H' => $carrier, 'E' => '承运'], JSON_UNESCAPED_UNICODE),
'created_at' => now(), 'updated_at' => now(),
]);
}
/**
* 导入手工快递汇总表的「汇总」工作表,整月替换。表头在第 2、3 行,承运商在 H 列。
*
* @return array{rows:int,title:?string}
*/
public function import(string $path, string $month): array
{
$reader = new BillWorkbookReader();
$target = null;
foreach ($reader->sheets($path, 'xlsx') as $name => $rows) {
if ($name === '汇总') {
$target = $rows;
break;
}
}
if ($target === null) {
throw new RuntimeException('文件里没有名为「汇总」的工作表。');
}
$letters = array_keys(self::COLUMNS);
$records = [];
$title = null;
$headerSeen = false;
foreach ($target as $number => $row) {
if (! $headerSeen) {
if ($title === null && trim((string) ($row[2] ?? '')) !== '') {
$title = trim((string) $row[2]);
}
if (trim((string) ($row[7] ?? '')) === '承运商') {
$headerSeen = true;
}
continue;
}
$carrier = trim((string) ($row[7] ?? ''));
if ($carrier === '' || $carrier === '承运商' || str_contains($carrier, '合计')) {
continue;
}
$cells = [];
foreach ($letters as $index => $letter) {
$value = trim((string) ($row[$index] ?? ''));
if (in_array($letter, self::MONEY, true)) {
$cells[$letter] = BillParser::number($value);
} elseif (in_array($letter, ['A', 'B', 'AB'], true)) {
$cells[$letter] = self::date($value);
} else {
$cells[$letter] = $value === '' || $value === '0' ? null : $value;
}
}
$records[$carrier] = $cells;
}
if ($records === []) {
throw new RuntimeException('没有读到承运商行(H 列「承运商」表头下面)。');
}
$this->db()->transaction(function () use ($records, $month): void {
$this->db()->table('courier_payable_summary_rows')->where('month', $month)->delete();
$sort = 0;
foreach ($records as $carrier => $cells) {
$this->db()->table('courier_payable_summary_rows')->insert([
'month' => $month, 'sort' => ++$sort, 'carrier' => (string) $carrier,
'cells' => json_encode($cells, JSON_UNESCAPED_UNICODE), 'created_at' => now(), 'updated_at' => now(),
]);
}
});
return ['rows' => count($records), 'title' => $title];
}
/** 导出:格式同手工快递汇总表(标题行 + 两行表头 + 数据 + 合计)。 */
public function export(string $month, $output): void
{
$rows = $this->rows($month);
$book = new StreamingWorkbook();
$companies = array_count_values(array_filter(array_map(static fn (array $r): string => (string) ($r['cells']['C'] ?? ''), $rows)));
arsort($companies);
$company = (string) (array_key_first($companies) ?? '');
[$year, $m] = explode('-', $month);
$title = array_fill(0, count(self::COLUMNS), null);
$title[2] = $company . $year . '年应付' . (int) $m . '月份快递、物流运费清单';
$book->row('汇总', $title, true);
$letters = array_keys(self::COLUMNS);
$groupHeader = array_fill(0, count($letters), null);
$header = [];
foreach ($letters as $index => $letter) {
$header[] = self::COLUMNS[$letter];
}
$groupHeader[array_search('AF', $letters, true)] = '差异明细';
$book->row('汇总', $groupHeader, true);
$book->row('汇总', $header, true);
$totals = array_fill_keys(self::MONEY, 0.0);
foreach ($rows as $index => $row) {
$cells = $row['cells'];
$cells['F'] = $index + 1;
$line = [];
foreach ($letters as $letter) {
$value = $cells[$letter] ?? null;
if (in_array($letter, self::MONEY, true)) {
$value = $value === null || $value === '' ? 0.0 : round((float) $value, 2);
$totals[$letter] += $value;
} elseif ($letter === 'F') {
$value = (int) $value;
} else {
$value = $value === null ? null : (string) $value;
}
$line[] = $value;
}
$book->row('汇总', $line);
}
$sum = [];
foreach ($letters as $letter) {
$sum[] = $letter === 'H' ? '合计' : (in_array($letter, self::MONEY, true) ? round($totals[$letter], 2) : null);
}
$book->row('汇总', $sum, true);
$book->writeTo($output);
}
public static function date(mixed $value): ?string
{
$value = trim((string) $value);
if ($value === '' || $value === '0') {
return null;
}
if (preg_match('/^\d{5}(\.\d+)?$/', $value)) {
return gmdate('Y-m-d', (int) round(((float) $value - 25569) * 86400));
}
if (preg_match('/^(\d{4})[\/\-.](\d{1,2})[\/\-.](\d{1,2})/', $value, $m)) {
return sprintf('%04d-%02d-%02d', $m[1], $m[2], $m[3]);
}
return $value;
}
}