- 报销金额公式:空包费改为加(任务付款+快递费+佣金+京喜差价−扣款+空包费) - 去掉「以旧换新超买家实付」「查不到标签待复查」两项校验 - 种菜额度不再上传看板:按《种菜明细报表生成逻辑》(业务交付包 2026-11-27)自算, 商品ID→ID负责人、职级、店铺信息直接只读查经营分析副本库(JSReportReplica.rpt), 金额取实付金额字段(同看板);单笔/每日/月度超额、未匹配负责人、职级为空、职级未配置、 额度规则未配置全部取消;额度数据取不到时整批待复查 - 额度规则 309 条(脉象导出)随代码初始化,工作台可新增/修改/删除/整体导入/导出 - 利润中心直接读工作平台店铺信息(rpt.fys_shopInfo),查不到改为待复查;去掉店铺信息、看板上传 - 种菜任务工单导入模板执行人统一填李斯 - 每日群汇总推送改到 11:20(部署脚本 cron) - 用看板 11 月 1–27 日 13,941 单对照:规则来源、日/月累计、风险类型逐单一致 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UNTa9ohkCsVFACqjz3KMcG
428 lines
20 KiB
PHP
428 lines
20 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
/**
|
||
* 种菜报销工作台:对一批待报销的种菜工单逐单校验,并汇总出打款明细、钉钉流程明细和种菜任务工单。
|
||
*
|
||
* 规则(2026-11-12 报销人逐条确认,2026-11-27 调整):
|
||
* - 重复报销:线上订单号在当月或上月已报销过 → 取消;
|
||
* - 报销金额:最终报销金额 ≠ 任务付款金额 + 任务快递费 + 任务佣金 + 京喜差价 − 任务扣款费用 + 任务空包费 → 取消;
|
||
* - 佣金资格:任务佣金 ≠ 0 且发起人不在「报销佣金人员」名单 → 取消;
|
||
* - 收款人在职:收款人不在花名册在职名单(例外名单除外)→ 取消;
|
||
* - 种菜额度(财务系统按《种菜明细报表生成逻辑》自算,口径同「脉象」每日种菜监控看板):
|
||
* 单笔 / 每日 / 月度超额、未匹配负责人、职级为空、职级未配置、额度规则未配置 → 全部取消;
|
||
* 额度数据取不到(经营分析副本库连接失败)→ 待复查;
|
||
* - 店铺在工作平台店铺信息里查不到利润中心 → 待复查。
|
||
*
|
||
* 纯计算类:不读数据库,输入由工作台数据层准备,便于测试与对照。
|
||
*/
|
||
final class PlantingReimbursementAuditor
|
||
{
|
||
public const DECISION_PASS = 'pass';
|
||
|
||
public const DECISION_CANCEL = 'cancel';
|
||
|
||
public const DECISION_RECHECK = 'recheck';
|
||
|
||
public const DECISION_LABELS = [
|
||
self::DECISION_PASS => '可报销',
|
||
self::DECISION_CANCEL => '取消工单',
|
||
self::DECISION_RECHECK => '待复查',
|
||
];
|
||
|
||
/** 单独成组、钉钉流程里一店一行的三家天猫店(钉钉表单里的店铺简称)。 */
|
||
public const BIG_TMALL_SHOPS = [
|
||
'天猫-欧意朗旗舰店' => '欧意朗',
|
||
'天猫-亿家达旗舰店' => '亿家达',
|
||
'天猫-卓禾家具旗舰店' => '卓禾',
|
||
];
|
||
|
||
public const GROUP_BIG_TMALL = '三大天猫';
|
||
|
||
public const GROUP_OTHER = '其他';
|
||
|
||
/** 种菜任务工单里非三大天猫店铺统一填写的店铺名称。 */
|
||
public const SAMPLE_SHOP = '样品专用店铺';
|
||
|
||
public const ISSUE_DUPLICATE = 'duplicate';
|
||
|
||
public const ISSUE_AMOUNT = 'amount';
|
||
|
||
public const ISSUE_COMMISSION = 'commission';
|
||
|
||
public const ISSUE_ROSTER = 'roster';
|
||
|
||
public const ISSUE_OVER_LIMIT = 'over_limit';
|
||
|
||
public const ISSUE_OWNER_MISSING = 'owner_missing';
|
||
|
||
public const ISSUE_RANK_MISSING = 'rank_missing';
|
||
|
||
public const ISSUE_RANK_UNCONFIGURED = 'rank_unconfigured';
|
||
|
||
public const ISSUE_RULE_MISSING = 'rule_missing';
|
||
|
||
public const ISSUE_QUOTA_UNAVAILABLE = 'quota_unavailable';
|
||
|
||
public const ISSUE_PROFIT_CENTER = 'profit_center';
|
||
|
||
public const ISSUE_LABELS = [
|
||
self::ISSUE_DUPLICATE => '重复报销',
|
||
self::ISSUE_AMOUNT => '金额不符',
|
||
self::ISSUE_COMMISSION => '无佣金资格',
|
||
self::ISSUE_ROSTER => '收款人不在职',
|
||
self::ISSUE_OVER_LIMIT => '超额',
|
||
self::ISSUE_OWNER_MISSING => '未匹配负责人',
|
||
self::ISSUE_RANK_MISSING => '职级为空',
|
||
self::ISSUE_RANK_UNCONFIGURED => '职级未配置',
|
||
self::ISSUE_RULE_MISSING => '额度规则未配置',
|
||
self::ISSUE_QUOTA_UNAVAILABLE => '额度未校验',
|
||
self::ISSUE_PROFIT_CENTER => '利润中心待补',
|
||
];
|
||
|
||
/** 只判待复查、不取消的问题。 */
|
||
public const RECHECK_ISSUES = [self::ISSUE_QUOTA_UNAVAILABLE, self::ISSUE_PROFIT_CENTER];
|
||
|
||
/** 额度计算的风险类型 → 工作台问题(都取消)。 */
|
||
private const QUOTA_ISSUES = [
|
||
PlantingQuotaCalculator::TYPE_OWNER_MISSING => self::ISSUE_OWNER_MISSING,
|
||
PlantingQuotaCalculator::TYPE_RANK_MISSING => self::ISSUE_RANK_MISSING,
|
||
PlantingQuotaCalculator::TYPE_RANK_UNCONFIGURED => self::ISSUE_RANK_UNCONFIGURED,
|
||
PlantingQuotaCalculator::TYPE_RULE_MISSING => self::ISSUE_RULE_MISSING,
|
||
];
|
||
|
||
/**
|
||
* @param list<array<string,mixed>> $rows 工单行(PlantingReimbursementRepository 的字段)
|
||
* @param array{
|
||
* reimbursed?: array<string,string>,
|
||
* commission_people?: array<string,bool>,
|
||
* roster?: array<string,bool>|null,
|
||
* roster_exceptions?: list<string>,
|
||
* profit_centers?: array<string,string>,
|
||
* quota?: array<string,array<string,mixed>>|null,
|
||
* quota_error?: string,
|
||
* } $refs
|
||
* @return array{rows:list<array<string,mixed>>,summary:array<string,mixed>}
|
||
*/
|
||
public function audit(array $rows, array $refs, string $reimburseDate): array
|
||
{
|
||
$reimbursed = $refs['reimbursed'] ?? [];
|
||
$commission = $refs['commission_people'] ?? [];
|
||
$roster = array_key_exists('roster', $refs) ? $refs['roster'] : [];
|
||
$rosterExceptions = array_map([self::class, 'normName'], $refs['roster_exceptions'] ?? []);
|
||
$centers = $refs['profit_centers'] ?? [];
|
||
// 没传 quota 表示不做额度校验(测试与回放用);传 null 表示额度数据取不到。
|
||
$quotaChecked = array_key_exists('quota', $refs);
|
||
$quota = $refs['quota'] ?? null;
|
||
$quotaError = trim((string) ($refs['quota_error'] ?? ''));
|
||
|
||
$results = [];
|
||
$seen = [];
|
||
foreach ($rows as $row) {
|
||
$orderNo = trim((string) ($row['online_order_no'] ?? ''));
|
||
$shop = trim((string) ($row['shop_name'] ?? ''));
|
||
$issues = [];
|
||
|
||
if ($orderNo !== '' && isset($reimbursed[$orderNo])) {
|
||
$issues[] = $this->issue(self::ISSUE_DUPLICATE, '重复报销:该单已在 ' . $reimbursed[$orderNo] . ' 报销过');
|
||
} elseif ($orderNo !== '' && isset($seen[$orderNo])) {
|
||
$issues[] = $this->issue(self::ISSUE_DUPLICATE, '重复报销:本批次工单 ' . $seen[$orderNo] . ' 已报同一订单');
|
||
}
|
||
if ($orderNo !== '') {
|
||
$seen[$orderNo] ??= (string) ($row['work_order_no'] ?? '');
|
||
}
|
||
|
||
$expected = self::cents($row['task_payment'] ?? null) + self::cents($row['task_freight'] ?? null)
|
||
+ self::cents($row['task_commission'] ?? null) + self::cents($row['jingxi_price_diff'] ?? null)
|
||
- self::cents($row['task_deduction'] ?? null) + self::cents($row['task_empty_package_fee'] ?? null);
|
||
$final = self::cents($row['reimbursement_amount'] ?? null);
|
||
if ($expected !== $final) {
|
||
$issues[] = $this->issue(self::ISSUE_AMOUNT, sprintf(
|
||
'最终报销金额 %s 与明细合计 %s 不符(任务付款+快递费+佣金+京喜差价−扣款+空包费)',
|
||
self::money($final),
|
||
self::money($expected),
|
||
));
|
||
}
|
||
|
||
$initiator = self::normName((string) ($row['initiator'] ?? ''));
|
||
if (self::cents($row['task_commission'] ?? null) !== 0 && ! isset($commission[$initiator])) {
|
||
$issues[] = $this->issue(self::ISSUE_COMMISSION, '发起人 ' . $initiator . ' 不在报销佣金人员名单,不能报佣金');
|
||
}
|
||
|
||
$payee = self::normName((string) ($row['payee_name'] ?? ''));
|
||
if ($roster !== null && ! isset($roster[$payee]) && ! $this->isRosterException($payee, $rosterExceptions)) {
|
||
$issues[] = $this->issue(self::ISSUE_ROSTER, '收款人 ' . ($payee === '' ? '(空)' : $payee) . ' 不在在职花名册');
|
||
}
|
||
|
||
$risk = null;
|
||
if (! $quotaChecked) {
|
||
// 不校验额度。
|
||
} elseif ($quota === null) {
|
||
$issues[] = $this->issue(self::ISSUE_QUOTA_UNAVAILABLE, '种菜额度暂时无法校验' . ($quotaError !== '' ? '(' . $quotaError . ')' : '') . ',请稍后重新生成');
|
||
} else {
|
||
$risk = $quota[(string) ($row['work_order_no'] ?? '')] ?? null;
|
||
if ($risk === null) {
|
||
$issues[] = $this->issue(self::ISSUE_QUOTA_UNAVAILABLE, '工单缺少支付时间,种菜额度无法校验');
|
||
} else {
|
||
foreach ($this->quotaIssues($risk) as $issue) {
|
||
$issues[] = $issue;
|
||
}
|
||
}
|
||
}
|
||
|
||
$center = $centers[$shop] ?? '';
|
||
if ($center === '') {
|
||
$issues[] = $this->issue(self::ISSUE_PROFIT_CENTER, '店铺 ' . $shop . ' 在工作平台店铺信息里查不到所属利润中心,请先到工作平台补齐');
|
||
}
|
||
|
||
$results[] = $row + [
|
||
'issues' => $issues,
|
||
'risk' => $risk,
|
||
'quota_ider' => (string) ($risk['ider'] ?? ''),
|
||
'quota_level' => (string) ($risk['position_level'] ?? ''),
|
||
'quota_rule' => (string) ($risk['rule_label'] ?? ''),
|
||
'quota_amount' => $risk['amount'] ?? null,
|
||
'quota_day_total' => $risk['day_total'] ?? null,
|
||
'quota_day_limit' => $risk['day_limit'] ?? null,
|
||
'quota_month_total' => $risk['month_total'] ?? null,
|
||
'quota_month_limit' => $risk['month_limit'] ?? null,
|
||
'quota_message' => (string) ($risk['risk_message'] ?? ''),
|
||
'profit_center' => $center,
|
||
'group' => isset(self::BIG_TMALL_SHOPS[$shop]) ? self::GROUP_BIG_TMALL : self::GROUP_OTHER,
|
||
];
|
||
}
|
||
|
||
foreach ($results as &$result) {
|
||
$codes = array_column($result['issues'], 'code');
|
||
$blocking = array_diff($codes, self::RECHECK_ISSUES);
|
||
$result['decision'] = $blocking !== []
|
||
? self::DECISION_CANCEL
|
||
: ($codes !== [] ? self::DECISION_RECHECK : self::DECISION_PASS);
|
||
$result['decision_label'] = self::DECISION_LABELS[$result['decision']];
|
||
$result['issue_text'] = implode(';', array_column($result['issues'], 'message'));
|
||
}
|
||
unset($result);
|
||
|
||
return ['rows' => $results, 'summary' => $this->summarize($results, $reimburseDate)];
|
||
}
|
||
|
||
/**
|
||
* 额度计算结果 → 工作台问题:超额合成一条(原因用计算给的说明),其余风险类型各一条,都取消。
|
||
*
|
||
* @param array<string,mixed> $risk
|
||
* @return list<array{code:string,label:string,message:string}>
|
||
*/
|
||
private function quotaIssues(array $risk): array
|
||
{
|
||
$types = (array) ($risk['risk_types'] ?? []);
|
||
$issues = [];
|
||
foreach (self::QUOTA_ISSUES as $type => $code) {
|
||
if (in_array($type, $types, true)) {
|
||
$owner = trim((string) ($risk['ider'] ?? ''));
|
||
$issues[] = $this->issue($code, self::ISSUE_LABELS[$code] . ':' . ($owner !== '' ? 'ID负责人 ' . $owner . ',' : '') . trim((string) ($risk['risk_message'] ?? '')));
|
||
}
|
||
}
|
||
if (array_intersect(PlantingQuotaCalculator::OVER_TYPES, $types) !== []) {
|
||
$issues[] = $this->issue(self::ISSUE_OVER_LIMIT, '超额:' . trim((string) ($risk['risk_message'] ?? '')) . '(' . trim((string) ($risk['rule_label'] ?? '')) . ')');
|
||
}
|
||
|
||
return $issues;
|
||
}
|
||
|
||
/**
|
||
* @param list<array<string,mixed>> $results
|
||
* @return array<string,mixed>
|
||
*/
|
||
private function summarize(array $results, string $reimburseDate): array
|
||
{
|
||
$billDate = date('Y-m-d', strtotime($reimburseDate . ' -1 day'));
|
||
$purpose = (int) substr($billDate, 5, 2) . '.' . (int) substr($billDate, 8, 2) . '种菜报销';
|
||
|
||
$counts = array_fill_keys(array_keys(self::DECISION_LABELS), 0);
|
||
$amounts = array_fill_keys(array_keys(self::DECISION_LABELS), 0);
|
||
$groups = [self::GROUP_BIG_TMALL => 0, self::GROUP_OTHER => 0];
|
||
$pivots = [self::GROUP_BIG_TMALL => [], self::GROUP_OTHER => []];
|
||
$cards = [self::GROUP_BIG_TMALL => [], self::GROUP_OTHER => []];
|
||
$ding = [];
|
||
$notices = [];
|
||
|
||
foreach ($results as $row) {
|
||
$amount = self::cents($row['reimbursement_amount'] ?? null);
|
||
$counts[$row['decision']]++;
|
||
$amounts[$row['decision']] += $amount;
|
||
|
||
if ($row['decision'] !== self::DECISION_PASS) {
|
||
$initiator = self::normName((string) ($row['initiator'] ?? '')) ?: '(未知发起人)';
|
||
$notices[$initiator][] = [
|
||
'order_no' => (string) $row['online_order_no'],
|
||
'work_order_no' => (string) ($row['work_order_no'] ?? ''),
|
||
'decision' => $row['decision'],
|
||
'reason' => $row['issue_text'],
|
||
];
|
||
continue;
|
||
}
|
||
|
||
$group = $row['group'];
|
||
$shop = (string) $row['shop_name'];
|
||
$center = (string) $row['profit_center'];
|
||
$payee = (string) ($row['payee_name'] ?? '');
|
||
$account = (string) ($row['payee_account'] ?? '');
|
||
$groups[$group] += $amount;
|
||
|
||
$pivotKey = implode("\x1f", [$row['initiator'] ?? '', $center, $shop, $payee, $account]);
|
||
$pivots[$group][$pivotKey] ??= [
|
||
'initiator' => (string) ($row['initiator'] ?? ''), 'profit_center' => $center, 'shop_name' => $shop,
|
||
'payee_name' => $payee, 'payee_account' => $account, 'cents' => 0,
|
||
];
|
||
$pivots[$group][$pivotKey]['cents'] += $amount;
|
||
|
||
$cardKey = $group === self::GROUP_BIG_TMALL
|
||
? implode("\x1f", [$center, $shop, $payee, $account])
|
||
: implode("\x1f", [$center, $payee, $account]);
|
||
$cards[$group][$cardKey] ??= [
|
||
'profit_center' => $center, 'shop_name' => $group === self::GROUP_BIG_TMALL ? $shop : '',
|
||
'payee_name' => $payee, 'payee_account' => $account, 'payee_bank' => '', 'payee_mobile' => '', 'cents' => 0,
|
||
];
|
||
$cards[$group][$cardKey]['cents'] += $amount;
|
||
foreach (['payee_bank', 'payee_mobile'] as $field) {
|
||
if ($cards[$group][$cardKey][$field] === '' && trim((string) ($row[$field] ?? '')) !== '') {
|
||
$cards[$group][$cardKey][$field] = trim((string) $row[$field]);
|
||
}
|
||
}
|
||
|
||
$dingKey = $group === self::GROUP_BIG_TMALL ? 'S' . $shop : 'C' . $center;
|
||
$ding[$dingKey] ??= [
|
||
'department' => $center,
|
||
'shop' => $group === self::GROUP_BIG_TMALL ? self::BIG_TMALL_SHOPS[$shop] : '其他',
|
||
'purpose' => $purpose,
|
||
'payment_method' => '银行卡',
|
||
'cents' => 0,
|
||
'order' => $group === self::GROUP_BIG_TMALL ? array_search($shop, array_keys(self::BIG_TMALL_SHOPS), true) : 10,
|
||
];
|
||
$ding[$dingKey]['cents'] += $amount;
|
||
}
|
||
|
||
$sortBy = static function (array $rows, array $keys): array {
|
||
$rows = array_values($rows);
|
||
usort($rows, static function (array $a, array $b) use ($keys): int {
|
||
foreach ($keys as $key) {
|
||
$cmp = self::compareText((string) $a[$key], (string) $b[$key]);
|
||
if ($cmp !== 0) {
|
||
return $cmp;
|
||
}
|
||
}
|
||
|
||
return 0;
|
||
});
|
||
|
||
return $rows;
|
||
};
|
||
|
||
$dingLines = array_values($ding);
|
||
usort($dingLines, static fn (array $a, array $b): int => [$a['order'], $a['department']] <=> [$b['order'], $b['department']]);
|
||
|
||
$noticeList = [];
|
||
foreach ($notices as $initiator => $items) {
|
||
$noticeList[] = ['initiator' => $initiator, 'items' => $items, 'message' => self::noticeMessage($initiator, $items)];
|
||
}
|
||
usort($noticeList, static fn (array $a, array $b): int => self::compareText($a['initiator'], $b['initiator']));
|
||
|
||
// 自检:各汇总口径的合计必须一致。
|
||
$passCents = $amounts[self::DECISION_PASS];
|
||
$sumCents = static fn (array $lines): int => array_sum(array_column($lines, 'cents'));
|
||
$checks = [
|
||
['label' => '钉钉明细合计 = 可报销合计', 'ok' => $sumCents($dingLines) === $passCents],
|
||
['label' => '打款卡号明细合计 = 可报销合计', 'ok' => $sumCents($cards[self::GROUP_BIG_TMALL]) + $sumCents($cards[self::GROUP_OTHER]) === $passCents],
|
||
['label' => '种菜任务工单合计 = 可报销合计', 'ok' => $sumCents($pivots[self::GROUP_BIG_TMALL]) + $sumCents($pivots[self::GROUP_OTHER]) === $passCents],
|
||
['label' => '三大天猫 + 其他 = 可报销合计', 'ok' => array_sum($groups) === $passCents],
|
||
['label' => '可报销 + 取消 + 待复查 条数 = 取单条数', 'ok' => array_sum($counts) === count($results)],
|
||
['label' => '可报销 + 取消 + 待复查 金额 = 取单金额', 'ok' => array_sum($amounts) === $sumCents(array_map(static fn (array $row): array => ['cents' => self::cents($row['reimbursement_amount'] ?? null)], $results))],
|
||
];
|
||
|
||
return [
|
||
'checks' => $checks,
|
||
'source' => ['count' => count($results), 'amount' => self::money(array_sum($amounts))],
|
||
'reimburse_date' => $reimburseDate,
|
||
'bill_date' => $billDate,
|
||
'purpose' => $purpose,
|
||
'counts' => $counts,
|
||
'amounts' => array_map([self::class, 'money'], $amounts),
|
||
'group_amounts' => array_map([self::class, 'money'], $groups),
|
||
'total' => self::money(array_sum($groups)),
|
||
'pivots' => [
|
||
// 与手工数据透视表一致:按创建人排序。
|
||
self::GROUP_BIG_TMALL => $sortBy($pivots[self::GROUP_BIG_TMALL], ['initiator', 'profit_center', 'shop_name', 'payee_name']),
|
||
self::GROUP_OTHER => $sortBy($pivots[self::GROUP_OTHER], ['initiator', 'profit_center', 'shop_name', 'payee_name']),
|
||
],
|
||
'cards' => [
|
||
self::GROUP_BIG_TMALL => $sortBy($cards[self::GROUP_BIG_TMALL], ['profit_center', 'shop_name', 'payee_name']),
|
||
self::GROUP_OTHER => $sortBy($cards[self::GROUP_OTHER], ['profit_center', 'payee_name']),
|
||
],
|
||
'ding_lines' => $dingLines,
|
||
'notices' => $noticeList,
|
||
];
|
||
}
|
||
|
||
/** @param list<array<string,string>> $items */
|
||
private static function noticeMessage(string $initiator, array $items): string
|
||
{
|
||
$lines = [];
|
||
foreach ($items as $item) {
|
||
$lines[] = $item['order_no'] . ' ' . $item['reason'];
|
||
}
|
||
|
||
return implode("\n", $lines) . "\n@" . $initiator . ' 以上订单本次不予报销,请到聚工单取消工单;待复查的单稍后复核。';
|
||
}
|
||
|
||
private function isRosterException(string $payee, array $exceptions): bool
|
||
{
|
||
foreach ($exceptions as $exception) {
|
||
if ($exception !== '' && ($payee === $exception || str_starts_with($payee, $exception))) {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
/** @return array{code:string,label:string,message:string} */
|
||
private function issue(string $code, string $message): array
|
||
{
|
||
return ['code' => $code, 'label' => self::ISSUE_LABELS[$code], 'message' => $message];
|
||
}
|
||
|
||
public static function normName(string $name): string
|
||
{
|
||
return trim(preg_replace('/[\s\x{3000}]+/u', '', $name) ?? '');
|
||
}
|
||
|
||
public static function cents(mixed $value): int
|
||
{
|
||
if ($value === null || $value === '') {
|
||
return 0;
|
||
}
|
||
$normalized = str_replace([',', ',', '¥', '¥', '元', ' '], '', trim((string) $value));
|
||
if (! is_numeric($normalized)) {
|
||
return 0;
|
||
}
|
||
|
||
return (int) round(((float) $normalized) * 100);
|
||
}
|
||
|
||
public static function money(int $cents): string
|
||
{
|
||
return number_format($cents / 100, 2, '.', '');
|
||
}
|
||
|
||
private static function compareText(string $a, string $b): int
|
||
{
|
||
static $collator = false;
|
||
if ($collator === false) {
|
||
$collator = class_exists(\Collator::class) ? new \Collator('zh_CN') : null;
|
||
}
|
||
|
||
return $collator ? (int) $collator->compare($a, $b) : strcmp($a, $b);
|
||
}
|
||
}
|