CaiWuXiTong/modules/EcommerceFinance/Services/PlantingReimbursementIncomeCheck.php

126 lines
6.4 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 Carbon\CarbonImmutable;
use Modules\EcommerceFinance\Repositories\PlantingReimbursementIncomeRepository;
class PlantingReimbursementIncomeCheck
{
public const RESULTS = ['多报销', '少报销', '需核实', '未入账', '一致'];
public const DEFAULT_FROM = '2026-11-11';
public const SOURCE_LABELS = ['taobao-alipay' => '支付宝', 'taobao-wechat' => '淘系微信', 'pinduoduo' => '拼多多', 'jd-transactions' => '京东', 'jingxi' => '京喜', 'douyin' => '抖音'];
public function __construct(private readonly PlantingReimbursementIncomeRepository $bills) {}
public function status(): array
{
return $this->bills->status();
}
public static function orderNo(string $number): string
{
return preg_replace("/^[\\s'’]+/u", '', $number) ?? $number;
}
public static function cents(mixed $value): int
{
// 淘系镜像使用四位小数保存金额,末尾补零不改变分值。
if (! preg_match('/^(-?)(\d+)(?:\.(\d{1,2})0*)?$/', trim((string) $value), $m)) return 0;
$amount = (int) $m[2] * 100 + (int) str_pad($m[3] ?? '', 2, '0');
return ($m[1] === '-' ? -1 : 1) * $amount;
}
public static function decimal(int $cents): string
{
return ($cents < 0 ? '-' : '') . intdiv(abs($cents), 100) . '.' . str_pad((string) (abs($cents) % 100), 2, '0', STR_PAD_LEFT);
}
public static function sources(array $row): array
{
return match ((string) ($row['platform'] ?? '')) {
'淘宝天猫', '阿里巴巴' => ['taobao-alipay', 'taobao-wechat'],
'拼多多' => ['pinduoduo'],
'京东商城', '京东厂家直送' => [str_contains($row['shop_name'] ?? '', '京喜') ? 'jingxi' : 'jd-transactions'],
'头条放心购' => ['douyin'],
default => [],
};
}
public static function billFrom(array $row): ?string
{
$date = substr(str_replace('/', '-', (string) ($row['paid_at'] ?? '')), 0, 10);
if (! preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) || ! checkdate((int) substr($date, 5, 2), (int) substr($date, 8, 2), (int) substr($date, 0, 4))) return null;
return CarbonImmutable::parse($date)->startOfMonth()->subMonthNoOverflow()->day(25)->format('Y-m-d');
}
/** 每次从当前活动账单计算,导入/同步后无需手工刷新核对结果。 */
public function rows(array $rows): array
{
if ($rows === []) return [];
$orders = []; $from = today()->format('Y-m-d');
foreach ($rows as $row) {
$start = self::billFrom($row);
$number = self::orderNo((string) $row['online_order_no']);
if ($start === null || $number === '') continue;
$from = min($from, $start);
foreach (self::sources($row) as $source) $orders[$source][] = $number;
}
$status = $this->bills->status();
$index = []; $seen = [];
foreach ($this->bills->records($orders, $from . ' 00:00:00', today()->addDay()->format('Y-m-d') . ' 00:00:00') as $bill) {
$key = $bill['source'] . ':' . $bill['record_code'];
if (isset($seen[$key])) continue;
$seen[$key] = true;
$index[$bill['source']][(string) $bill['online_order_no']][] = $bill;
}
foreach ($rows as &$row) {
$number = self::orderNo((string) $row['online_order_no']);
$start = self::billFrom($row);
$sources = self::sources($row);
$income = $count = $discount = 0; $last = ''; $used = []; $other = [];
foreach ($sources as $source) foreach ($index[$source][$number] ?? [] as $bill) {
if ($start === null || $bill['occurred_at'] < $start) continue;
$net = self::cents($bill['income']) - self::cents($bill['expense']);
$remark = $bill['ledger_remark'] ?? $bill['payload']['ledger_remark'] ?? '';
if ($remark === '订单收入') {
$income += $net; $count++;
$used[$source] = self::SOURCE_LABELS[$source];
$last = max($last, $bill['occurred_at']);
} else {
if ($remark === '优惠收入') $discount += $net;
$other[] = self::SOURCE_LABELS[$source] . ' ' . $bill['bill_item'] . ' ' . self::decimal($net) . '元(' . $bill['record_code'] . ')';
}
}
$difference = self::cents($row['task_payment']) - $income;
$note = '';
$valid = $sources !== [] && $number !== '' && $start !== null && is_numeric($row['task_payment'] ?? null);
if (! $valid) {
$result = '需核实';
$note = $sources === [] ? '平台账单来源未配置' : '线上订单号、付款时间或任务付款金额缺失,请核实';
} elseif ($count > 0) {
$result = $difference > 1 ? '多报销' : ($difference < -1 ? '少报销' : '一致');
if ($result === '多报销') {
$note = '需找运营追回';
if ($discount !== 0) $note .= ';优惠收入(平台补贴/优惠券)' . self::decimal($discount) . '元,仍算多报销';
}
} elseif (in_array($sources[0], ['jd-transactions', 'jingxi'], true)
&& ($status['jd_through'] === null || substr($row['paid_at'], 0, 10) > $status['jd_through'])) {
$result = '未入账'; $note = '京东账单尚未导入';
} elseif (($row['platform_order_status'] ?? '') === 'TRADE_FINISHED') {
$result = '需核实';
$note = $other === [] ? '账单无该订单记录,可能未同步' : implode(';', $other);
if ($sources === ['douyin'] && $status['douyin_failed']) $note .= ';抖音原始账单同步异常';
} else {
$result = '未入账'; $note = '买家未确认收货';
}
$row = array_replace($row, ['income_total' => $valid ? self::decimal($income) : null, 'income_count' => $count,
'income_sources' => implode('、', $used), 'income_latest_at' => $last,
'income_difference' => $valid ? self::decimal($difference) : null,
'income_result' => $result, 'income_note' => $note]);
}
unset($row);
return $rows;
}
}