CaiWuXiTong/modules/EcommerceFinance/Services/PlantingReimbursementWorkbench.php
limeng b5244362a1 feat(种菜报销): 佣金人员可维护、自动放行检查、自动发通知、一键提交钉钉流程
- 报销佣金人员改为工作台维护(新增 / 移除 / 追加导入 / 导出),首次读取时自动导入以前上传的历史名单
- 去掉「去聚工单人工核对、勾选已核对」:改为放行检查(聚工单 20 分钟内同步过、额度已校验、
  规则不为空、自检全过、有可报销单),不通过不许导出 / 发通知 / 提交,并在页面列出原因
- 每天 11:20 汇总任务放行检查通过后自动发不予报销通知(@ 发起人,同一批不重发)
- 一键提交钉钉「种菜报销流程」(PROC-C5159B8D…):发起人李斯(按钉钉花名册查 userId),
  按钉钉表单实际结构自动填(收款费用明细 / 收款合计 / 收款人·开户行·账号=账号详见附件 /
  付款明细 / 报销类型=种菜核销),打款明细 xlsx 上传审批钉盘作附件;先可预览,
  缺必填 / 选项不匹配不许提交;同一账单日只提交一次,结果不确定记待核查
- 新配置 config/planting_reimbursement.php(凭据默认沿用快递入驻的财务系统钉钉应用,
  需补 PLANTING_DINGTALK_AGENT_ID)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UNTa9ohkCsVFACqjz3KMcG
2026-12-01 05:56:51 +00:00

243 lines
10 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 InvalidArgumentException;
use Modules\EcommerceFinance\Repositories\GenericBusinessMirrorRepository;
use Modules\EcommerceFinance\Repositories\PlantingReimbursementRepository as Repository;
use Throwable;
/**
* 种菜报销工作台数据层:取一批待报销工单 + 参考名单,交给审核器逐单判定并汇总。
*
* 利润中心、平台、店长直接读工作平台店铺信息(经营分析副本库),种菜额度由 PlantingQuotaCalculator 自算,不再上传看板和店铺信息。
*
* 锁单口径(2026-11-12 报销人确认):聚工单种菜报销、工单状态「待处理」、订单付款时间 [D−7 00:00:00, D−1 23:59:59]、
* ERP订单状态不为取消 / 删除 / 空、售后单号为空。
*/
class PlantingReimbursementWorkbench
{
/** 收款人不在花名册也照常报销的例外。 */
public const ROSTER_EXCEPTIONS = ['柴嘉伟(建行)', '柴嘉伟'];
/** 聚水潭订单镜像(ERP订单标签兜底)。 */
public const ERP_ORDER_TABLE = 'ops_jst_qmcust_orders';
public function __construct(
private readonly Repository $repository,
private readonly PlantingReimbursementReferences $references,
private readonly PlantingReimbursementAuditor $auditor,
private readonly PlantingReimbursementDirectory $directory,
private readonly PlantingQuotaDimensions $dimensions,
private readonly PlantingQuotaRules $rules,
private readonly PlantingQuotaCalculator $calculator,
private readonly PlantingCommissionPeople $commissionPeople,
) {}
public static function defaultDate(?CarbonImmutable $now = null): string
{
return ($now ?? CarbonImmutable::now())->format('Y-m-d');
}
/** 取单范围:待处理(锁单前,默认)/ 处理中(已锁单)/ 两者。 */
public const SCOPES = [
'pending' => '待处理(锁单前)',
'locked' => '处理中(已锁单)',
'all' => '待处理 + 处理中',
];
/** @return list<string> */
public static function scopeStatuses(string $scope): array
{
return match ($scope) {
'locked' => [Repository::STATUS_LOCKED],
'all' => Repository::OPEN_STATUSES,
default => [Repository::STATUS_PENDING],
};
}
/** 默认付款起始日:报销日往前 7 天。 */
public static function defaultPaidFrom(string $date): string
{
return self::parseDate($date)->subDays(7)->format('Y-m-d');
}
/** @return array{from:string,to:string} 订单付款时间窗口 [起始日 00:00:00, 报销日前一天 23:59:59] */
public static function paidWindow(string $date, ?string $paidFrom = null): array
{
$day = self::parseDate($date);
$from = $paidFrom === null || $paidFrom === '' ? $day->subDays(7) : self::parseDate($paidFrom);
if ($from->greaterThanOrEqualTo($day) || $from->lessThan($day->subDays(31))) {
throw new InvalidArgumentException('付款起始日须在报销日前 1~31 天内。');
}
return [
'from' => $from->format('Y-m-d 00:00:00'),
'to' => $day->subDay()->format('Y-m-d 23:59:59'),
];
}
public static function parseDate(string $date): CarbonImmutable
{
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) !== 1 || $date < '2026-09-09') {
throw new InvalidArgumentException('报销日期无效。');
}
$parsed = CarbonImmutable::createFromFormat('!Y-m-d', $date);
if ($parsed === false || $parsed->format('Y-m-d') !== $date) {
throw new InvalidArgumentException('报销日期无效。');
}
return $parsed;
}
/**
* @param list<string>|null $statuses 默认只取「待处理」
* @return array{rows:list<array<string,mixed>>,summary:array<string,mixed>,window:array{from:string,to:string},uploads:array<string,mixed>}
*/
public function build(int $companyId, string $date, ?string $paidFrom = null, ?array $statuses = null): array
{
$window = self::paidWindow($date, $paidFrom);
$rows = $this->fillErpLabels($this->repository->pendingRows($window['from'], $window['to'], $statuses ?? [Repository::STATUS_PENDING]));
// 收款人在职:优先用上传的花名册;没上传就用钉钉花名册副本里的在职真名。
$roster = $this->references->nameSet($companyId, PlantingReimbursementReferences::KIND_ROSTER);
$rosterSource = 'upload';
if ($roster === []) {
$roster = $this->directory->activeNames();
$rosterSource = $roster === [] ? 'none' : 'dingtalk';
// 两边都取不到名单时不做在职校验(页面提示),避免把所有单误判为收款人不在职。
$roster = $roster === [] ? null : $roster;
}
// 店铺信息直接读工作平台(经营分析副本库 rpt.fys_shopInfo):利润中心、平台、店长。
$quotaRows = [];
$quotaError = '';
try {
$quotaRows = $this->repository->quotaRows(self::monthStart($window['from']));
} catch (Throwable $exception) {
report($exception);
$quotaError = '聚工单镜像未就绪';
}
$shopNames = array_merge(array_column($rows, 'shop_name'), array_column($quotaRows, 'shop_name'));
$shopInfo = $this->dimensions->shops($shopNames);
$profitCenters = array_filter(array_map(static fn (array $shop): string => $shop['profit_center'], $shopInfo['shops']), static fn (string $center): bool => $center !== '');
// 本月数据缓存 5 分钟,刚发起的工单可能还不在里面:把本批补进去,保证每张待报销工单都有额度结果。
$known = array_flip(array_column($quotaRows, 'work_order_no'));
foreach ($rows as $row) {
if (! isset($known[$row['work_order_no']])) {
$quotaRows[] = $row + ['status_code' => Repository::STATUS_PENDING];
}
}
$quota = null;
if ($quotaError === '') {
try {
$quota = $this->quota($companyId, $quotaRows, $shopInfo['shops']);
} catch (Throwable $exception) {
report($exception);
$quotaError = '经营分析副本库查询失败';
}
}
$refs = [
'reimbursed' => $this->repository->reimbursedOrders($date, array_column($rows, 'work_order_no')),
'commission_people' => $this->commissionPeople->nameSet($companyId),
'roster' => $roster,
'roster_exceptions' => self::ROSTER_EXCEPTIONS,
'profit_centers' => $profitCenters,
'quota' => $quota,
'quota_error' => $quotaError,
];
return $this->auditor->audit($rows, $refs, $date) + [
'window' => $window,
'roster_source' => $rosterSource,
'shop_source' => $shopInfo['source'],
'quota_error' => $quotaError,
'quota_rules' => ['count' => count($this->rules->all($companyId)), 'source' => $this->rules->document($companyId)['source']],
'sync' => $this->repository->syncStatus(),
'uploads' => $this->references->uploads($companyId),
];
}
/**
* 种菜额度:本月 1 日起的全部种菜工单 + 商品负责人 + 职级 + 额度规则 → 每张工单的风险判定。
*
* @param list<array<string,mixed>> $quotaRows
* @param array<string,array{platform:string,shop_head:string,profit_center:string}> $shops
* @return array<string,array<string,mixed>>
*/
public function quota(int $companyId, array $quotaRows, array $shops): array
{
$productIds = [];
foreach ($quotaRows as $row) {
foreach (preg_split('/[\r\n,]+/', (string) ($row['platform_product_id'] ?? '')) ?: [] as $id) {
if (trim($id) !== '') {
$productIds[trim($id)] = true;
}
}
}
$owners = $this->dimensions->owners(array_keys($productIds));
$names = array_merge(array_column($owners, 'ider'), array_column($shops, 'shop_head'));
$levels = $this->dimensions->levels(array_values(array_filter(array_map('strval', $names))));
return $this->calculator->calculate($quotaRows, $shops, $owners, $levels, $this->rules->all($companyId));
}
/** 月累计从付款区间起始日所在月的 1 日算起。 */
public static function monthStart(string $from): string
{
return substr($from, 0, 7) . '-01 00:00:00';
}
/**
* 工单里 ERP订单标签为空的(如部分以旧换新单),按线上订单号补查聚水潭订单镜像的标签。
*
* @param list<array<string,mixed>> $rows
* @return list<array<string,mixed>>
*/
private function fillErpLabels(array $rows): array
{
$missing = [];
foreach ($rows as $row) {
$orderNo = trim((string) ($row['online_order_no'] ?? ''));
if ($orderNo !== '' && trim((string) ($row['erp_order_label'] ?? '')) === '') {
$missing[] = $orderNo;
}
}
if ($missing === []) {
return $rows;
}
$labels = [];
try {
$connection = app(GenericBusinessMirrorRepository::class)->connection();
if ($connection->getSchemaBuilder()->hasTable(self::ERP_ORDER_TABLE)) {
// so_id 是字符串列,必须按字符串绑定,否则走不了索引。
foreach (array_chunk(array_values(array_unique(array_map('strval', $missing))), 500) as $chunk) {
foreach ($connection->table(self::ERP_ORDER_TABLE)->whereIn('so_id', $chunk)->get(['so_id', 'labels']) as $order) {
$label = trim((string) $order->labels);
if ($label !== '') {
$labels[(string) $order->so_id] = isset($labels[(string) $order->so_id]) ? $labels[(string) $order->so_id] . ',' . $label : $label;
}
}
}
}
} catch (Throwable $exception) {
report($exception);
}
foreach ($rows as &$row) {
$orderNo = trim((string) ($row['online_order_no'] ?? ''));
if (trim((string) ($row['erp_order_label'] ?? '')) === '' && isset($labels[$orderNo])) {
$row['erp_order_label'] = $labels[$orderNo];
}
}
unset($row);
return $rows;
}
}