feat: 增加OA流程科目管理费用页 #800

Merged
yueyang merged 1 commits from feature/yueyang-management-expenses-page into main 2026-10-30 20:46:18 +08:00
10 changed files with 3929 additions and 0 deletions

View File

@ -4708,6 +4708,7 @@ class Pages extends Controller
'product-costs' => $this->contentForProductCosts(),
'financial-analysis' => $this->contentForFinancialAnalysis(),
'oa-process' => $this->contentForProcessDetails(),
'management-expenses' => $this->contentForManagementExpenses(),
'labor-expenses' => $this->contentForLaborExpenses(),
'courier-surcharge' => $this->contentForCourierSurcharge($tab),
'courier-surcharge-settlement' => $this->contentForCourierSurchargeSettlementPage(),
@ -4751,6 +4752,12 @@ class Pages extends Controller
return $data;
}
protected function contentForManagementExpenses(): array
{
return app(\Modules\EcommerceFinance\View\ManagementExpensesPageData::class)
->page(request());
}
protected function contentForLaborExpenses(): array
{
$saved = app(LaborExpenseDataStore::class)->load();

View File

@ -0,0 +1,95 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('oa_process_account_mapping')) {
$schema->create('oa_process_account_mapping', function (Blueprint $table): void {
$table->string('account_code', 64)->primary();
$table->string('account_name', 255);
$table->string('expense_category', 100)->index();
$table->string('second_level', 100)->nullable()->index();
$table->string('third_level', 100)->nullable()->index();
$table->boolean('in_fee_ratio')->default(false)->index();
$table->string('allocation', 100)->nullable();
$table->timestamps();
});
}
if ($schema->hasTable('ding_process_detail_mirror')
&& ! $schema->hasIndex('ding_process_detail_mirror', 'ding_process_detail_account_code_index')) {
$schema->table('ding_process_detail_mirror', function (Blueprint $table): void {
$table->index('account_code', 'ding_process_detail_account_code_index');
});
}
$mapping = json_decode(
(string) file_get_contents(base_path('resources/data/oa_process_account_mapping.json')),
true,
512,
JSON_THROW_ON_ERROR,
);
$connection = Schema::connection($this->connection());
$database = $connection->getConnection();
$now = now();
foreach (array_chunk($mapping, 100) as $chunk) {
$database->table('oa_process_account_mapping')->upsert(
array_map(static fn (array $row): array => [
'account_code' => (string) $row['account_code'],
'account_name' => (string) $row['account_name'],
'expense_category' => (string) $row['expense_category'],
'second_level' => $row['second_level']
?? ((string) $row['expense_category'] . '(未细分)'),
'third_level' => $row['third_level'] ?? '未细分',
'in_fee_ratio' => (bool) $row['in_fee_ratio'],
'allocation' => $row['allocation'] ?? null,
'created_at' => $now,
'updated_at' => $now,
], $chunk),
['account_code'],
[
'account_name',
'expense_category',
'second_level',
'third_level',
'in_fee_ratio',
'allocation',
'updated_at',
],
);
}
}
public function down(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if ($schema->hasTable('ding_process_detail_mirror')
&& $schema->hasIndex('ding_process_detail_mirror', 'ding_process_detail_account_code_index')) {
$schema->table('ding_process_detail_mirror', function (Blueprint $table): void {
$table->dropIndex('ding_process_detail_account_code_index');
});
}
$schema->dropIfExists('oa_process_account_mapping');
}
};

View File

@ -34,6 +34,7 @@
| 本次接入 | 普通商品资料的工作平台采购价格接入 `jiansun.dbo.pm_priceAdjustment`(镜像 `js_pm_price_adjustment`):按 `skuCode` 关联 `jst_sku.sku_id`,取 `effectTime` 不晚于当前时间的最新 `purchasePrice`,并在页面和导出中标记“工作平台价格”;源表没有可靠更新时间,按 `Id` 稳定键追加,首次全量完成前只显示普通商品自身采购价。 |
| 待有效凭据后首次同步 | 普通商品当前成本价、商品类型和更新时间继续读取 `operations_replica.rpt.jst_sku`;`rpt.fys_skuCostPriceUpdate` 是一 SKU 一行的旧快照,不能充当变价历史。完整成本价变更仍读取聚水潭经典开放平台“商品操作日志查询”接口 `worklog.query`,只镜像操作内容含“采购价”的记录到 `jushuitan_cost_price_history_rows`;经典接口必须在服务器私有配置中使用同一应用的 `JUSHUITAN_PARTNER_ID / JUSHUITAN_PARTNER_KEY / JUSHUITAN_TOKEN`,不得把新开放平台的 App Key / App Secret / Access Token 混用。页面在首次同步完成前明确显示待同步或失败,不把 0 条解释为真实无历史。 |
| 本次接入 | 流程明细读取 `operations_replica/rpt.ding_Workflow + rpt.ding_WorkflowScheme` 的结构化审批主表、费用明细和付款明细,写入 `ding_process_detail_mirror` 与 `ding_process_payment_mirror`;主表的 `originatorDeptName` 作为发起人部门单独保留。禁止先把明细表和付款表铺平成 CSV 后逐行求和;付款明细必须按“对应序号”关联到代表明细行,但合计始终读取独立付款事实。每个纳入范围的源审批至少保留一条页面记录,没有费用金额的审批以空金额显示,不静默隐藏。首次全量先运行 `business-mirror:sync-ding-process-details --full --dry-run` 校验,再使用 `business-mirror:sync-ding-process-details --full` 发布;日常通过 `updateAt/createAt` 48 小时重叠增量同步。当前纳入日常报销、应付、线上代发、种菜、快递面单、固定资产、日常物品、样品、一次性采买、板材、工资、外贸费用和种菜充值等 14 个财务流程;发现新的明细流程编码时全量同步报错并保留上一版。 |
| 本次接入 | 财务经营报表 › 管理费用使用 `oa_process_account_mapping` 保存“流程科目映射”工作簿中的 191 个科目编码、科目名称、费用大类、二级、三级、是否进费比和是否分摊规则;页面只读取 OA 流程中付款状态为“已付款”的明细,按费用大类和二级汇总进费比/不进费比/未映射金额,点击二级查看三级汇总与 9 列明细模板。 |
流程明细另设独立定时任务,避免与每分钟科目映射消费争用同一上游目录时被静默跳过。正式发布脚本会覆盖安装 `/etc/cron.d/caiwu-ding-process-details`:每 5 分钟尝试运行 `business-mirror:sync-ding-process-details`,使用独立调度锁并在共用上游锁上最多等待 15 分钟;`scripts/install-ding-process-sync-cron.ps1` 仅作为手工修复入口。任务时间和镜像状态统一使用平台固定时区,审批等待时长按实际小时展示。OA 页面每小时最多把一次当前页“审批中”的审批编号写入定向刷新队列,由每分钟检查一次的批处理命令消费;其他时间直接展示最近镜像,已完成流程不进入即时刷新链路,仍由常规增量和每周全量校准处理付款等后续变化。增量同步除跟进审批主表更新时间外,还以 `ding_WorkflowScheme` 的数字 `id` 高水位发现后补表单行,避免付款明细等新组件写入后主审批 `updateAt` 不变而被漏掉;原地改写同一组件仍由每周全量校准兜底。付款状态只按钉钉“出纳打款”节点判断,分为“出纳状态待同步 / 出纳未开始 / 出纳待打款 / 出纳退回 / 出纳已打款 / 流程终止 / 不涉及付款”。金额差异不参与付款状态判断,另以“付款差额 = 费用合计 − 已付款合计”展示。不能因为金额存在少量差异就覆盖出纳节点事实,也不能因为出纳已通过就隐藏金额差异。

View File

@ -0,0 +1,30 @@
<?php
namespace Modules\EcommerceFinance\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\View\ManagementExpensesPageData;
use Throwable;
class ManagementExpenses extends Controller
{
public function details(Request $request, ManagementExpensesPageData $pageData): JsonResponse
{
try {
return response()
->json(['success' => true, ...$pageData->details($request)])
->header('Cache-Control', 'no-store');
} catch (Throwable $exception) {
report($exception);
return response()
->json([
'success' => false,
'message' => '管理费用明细暂时无法读取,请稍后重试。',
], 503)
->header('Cache-Control', 'no-store');
}
}
}

View File

@ -0,0 +1,517 @@
<?php
namespace Modules\EcommerceFinance\View;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Query\Builder;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Throwable;
class ManagementExpensesPageData
{
public const PER_PAGE_OPTIONS = [50, 100, 200];
public const DEFAULT_PER_PAGE = 50;
public const FEE_RATIO_OPTIONS = [
'in' => '进费比',
'out' => '不进费比',
'unmapped' => '未映射科目',
];
public const DETAIL_COLUMNS = [
'business_id' => '审批编号',
'originator_department' => '部门',
'purpose' => '用途',
'expense_category' => '分类',
'second_level' => '二级',
'third_level' => '三级',
'amount' => '金额',
'fee_ratio' => '是否进费比',
'allocation' => '是否分摊',
];
private readonly ConnectionInterface $connection;
public function __construct(DatabaseManager $database)
{
$this->connection = $database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/** @return array<string,mixed> */
public function page(Request $request): array
{
$filters = $this->filters($request);
$page = max(1, (int) $request->query('page', 1));
$perPage = self::perPage($request->query('per_page'));
try {
$secondLevel = $this->secondLevelSummary($filters);
$thirdLevel = $this->thirdLevelSummary($filters);
$details = $this->detailResult($filters, $page, $perPage);
$options = $this->options();
return [
'view' => 'business.pages.financial-operations.management-expenses',
'pageTitle' => '管理费用',
'rows' => new LengthAwarePaginator(
$details['rows'],
$details['pagination']['total'],
$perPage,
$page,
[
'path' => $request->url(),
'query' => array_filter(
[...$filters, 'per_page' => $perPage],
static fn (mixed $value): bool => $value !== '' && $value !== null,
),
],
),
'filters' => $filters,
'summary' => $details['summary'],
'secondLevelSummary' => $secondLevel,
'thirdLevelSummary' => $thirdLevel,
'options' => $options,
'perPageOptions' => self::PER_PAGE_OPTIONS,
'detailColumns' => self::DETAIL_COLUMNS,
'detailsUrl' => route(
'business.financial-operations.management-expenses.details',
['company_id' => company_id() ?: 1],
),
'error' => null,
];
} catch (Throwable $exception) {
report($exception);
return [
'view' => 'business.pages.financial-operations.management-expenses',
'pageTitle' => '管理费用',
'rows' => new LengthAwarePaginator([], 0, $perPage, $page, [
'path' => $request->url(),
'query' => $request->query(),
]),
'filters' => $filters,
'summary' => $this->emptySummary(),
'secondLevelSummary' => [],
'thirdLevelSummary' => [],
'options' => $this->emptyOptions(),
'perPageOptions' => self::PER_PAGE_OPTIONS,
'detailColumns' => self::DETAIL_COLUMNS,
'detailsUrl' => route(
'business.financial-operations.management-expenses.details',
['company_id' => company_id() ?: 1],
),
'error' => '管理费用数据暂时无法读取,请稍后重试。',
];
}
}
/** @return array<string,mixed> */
public function details(Request $request): array
{
$filters = $this->filters($request);
$page = max(1, (int) $request->query('page', 1));
$perPage = self::perPage($request->query('per_page'));
return $this->detailResult($filters, $page, $perPage);
}
/** @return array<string,string> */
public static function filters(Request $request): array
{
[$paidStart, $paidEnd] = self::dateRange(
$request->query('paid_start'),
$request->query('paid_end'),
);
$feeRatio = trim((string) $request->query('fee_ratio', ''));
if (! array_key_exists($feeRatio, self::FEE_RATIO_OPTIONS)) {
$feeRatio = '';
}
return [
'paid_start' => $paidStart,
'paid_end' => $paidEnd,
'expense_category' => mb_substr(trim((string) $request->query('expense_category', '')), 0, 100),
'second_level' => mb_substr(trim((string) $request->query('second_level', '')), 0, 100),
'third_level' => mb_substr(trim((string) $request->query('third_level', '')), 0, 100),
'fee_ratio' => $feeRatio,
'allocation' => mb_substr(trim((string) $request->query('allocation', '')), 0, 100),
'business_id' => mb_substr(trim((string) $request->query('business_id', '')), 0, 32),
'originator_department' => mb_substr(trim((string) $request->query('originator_department', '')), 0, 255),
'originator_name' => mb_substr(trim((string) $request->query('originator_name', '')), 0, 100),
'keyword' => mb_substr(trim((string) $request->query('keyword', '')), 0, 100),
];
}
/** @return list<array<string,mixed>> */
private function secondLevelSummary(array $filters): array
{
$category = $this->categoryExpression();
$second = $this->secondLevelExpression();
$rows = $this->baseQuery($filters)
->selectRaw("{$category} AS expense_category, {$second} AS second_level")
->selectRaw($this->amountSplitExpression())
->groupByRaw("{$category}, {$second}")
->orderByRaw('SUM(COALESCE(d.amount, 0)) DESC')
->orderByRaw("{$category}, {$second}")
->get();
return $rows->map(function (object $row): array {
$values = (array) $row;
$values['group_key'] = $this->groupKey(
(string) $values['expense_category'],
(string) $values['second_level'],
);
$values['amount_total'] = round((float) $values['amount_total'], 2);
$values['in_fee_ratio_amount'] = round((float) $values['in_fee_ratio_amount'], 2);
$values['non_fee_ratio_amount'] = round((float) $values['non_fee_ratio_amount'], 2);
$values['unmapped_amount'] = round((float) $values['unmapped_amount'], 2);
$values['row_count'] = (int) $values['row_count'];
$values['approval_count'] = (int) $values['approval_count'];
return $values;
})->all();
}
/** @return list<array<string,mixed>> */
private function thirdLevelSummary(array $filters): array
{
$category = $this->categoryExpression();
$second = $this->secondLevelExpression();
$third = $this->thirdLevelExpression();
$rows = $this->baseQuery($filters)
->selectRaw("{$category} AS expense_category, {$second} AS second_level, {$third} AS third_level")
->selectRaw($this->amountSplitExpression())
->groupByRaw("{$category}, {$second}, {$third}")
->orderByRaw('SUM(COALESCE(d.amount, 0)) DESC')
->orderByRaw("{$third}")
->get();
return $rows->map(function (object $row): array {
$values = (array) $row;
$values['group_key'] = $this->groupKey(
(string) $values['expense_category'],
(string) $values['second_level'],
);
$values['amount_total'] = round((float) $values['amount_total'], 2);
$values['in_fee_ratio_amount'] = round((float) $values['in_fee_ratio_amount'], 2);
$values['non_fee_ratio_amount'] = round((float) $values['non_fee_ratio_amount'], 2);
$values['unmapped_amount'] = round((float) $values['unmapped_amount'], 2);
$values['row_count'] = (int) $values['row_count'];
$values['approval_count'] = (int) $values['approval_count'];
return $values;
})->all();
}
/** @return array{rows:list<array<string,mixed>>,pagination:array<string,int>,summary:array<string,int|float>} */
private function detailResult(array $filters, int $page, int $perPage): array
{
$query = $this->baseQuery($filters);
$total = (clone $query)->count();
$rows = $query
->select([
'd.business_id',
'd.originator_department',
'd.purpose',
'd.amount',
'd.line_no',
'd.process_instance_id',
])
->selectRaw($this->categoryExpression() . ' AS expense_category')
->selectRaw($this->secondLevelExpression() . ' AS second_level')
->selectRaw($this->thirdLevelExpression() . ' AS third_level')
->selectRaw($this->feeRatioExpression() . ' AS fee_ratio')
->selectRaw($this->allocationExpression() . ' AS allocation')
->orderByDesc('d.paid_at')
->orderByDesc('d.business_id')
->orderBy('d.line_no')
->forPage($page, $perPage)
->get()
->map(static fn (object $row): array => [
'business_id' => (string) $row->business_id,
'originator_department' => (string) ($row->originator_department ?? ''),
'purpose' => (string) ($row->purpose ?? ''),
'expense_category' => (string) $row->expense_category,
'second_level' => (string) $row->second_level,
'third_level' => (string) $row->third_level,
'amount' => round((float) ($row->amount ?? 0), 2),
'fee_ratio' => (string) $row->fee_ratio,
'allocation' => (string) $row->allocation,
])
->all();
return [
'rows' => $rows,
'pagination' => [
'current_page' => $page,
'last_page' => max(1, (int) ceil($total / $perPage)),
'per_page' => $perPage,
'total' => $total,
],
'summary' => $this->summary($filters),
];
}
/** @return array<string,int|float> */
private function summary(array $filters): array
{
$row = $this->baseQuery($filters)
->selectRaw($this->amountSplitExpression())
->first();
$values = $row === null ? [] : (array) $row;
return [
'amount_total' => round((float) ($values['amount_total'] ?? 0), 2),
'in_fee_ratio_amount' => round((float) ($values['in_fee_ratio_amount'] ?? 0), 2),
'non_fee_ratio_amount' => round((float) ($values['non_fee_ratio_amount'] ?? 0), 2),
'unmapped_amount' => round((float) ($values['unmapped_amount'] ?? 0), 2),
'row_count' => (int) ($values['row_count'] ?? 0),
'approval_count' => (int) ($values['approval_count'] ?? 0),
];
}
private function baseQuery(array $filters): Builder
{
$query = $this->connection->table('ding_process_detail_mirror as d')
->leftJoin(
'oa_process_account_mapping as m',
'm.account_code',
'=',
'd.account_code',
)
->where(function (Builder $paid): void {
$paid->where('d.cashier_status', 'completed')
->orWhere(function (Builder $completed): void {
$completed->where('d.status', '已完成')
->whereNotNull('d.payment_source_state')
->where('d.payment_source_state', '<>', 'not_applicable');
});
});
if (($filters['paid_start'] ?? '') !== '') {
$query->where('d.paid_at', '>=', $filters['paid_start']);
}
if (($filters['paid_end'] ?? '') !== '') {
$query->where(
'd.paid_at',
'<',
\Illuminate\Support\Carbon::createFromFormat('Y-m-d', $filters['paid_end'])
->addDay()
->toDateString(),
);
}
if (($filters['expense_category'] ?? '') !== '') {
$query->whereRaw(
$this->categoryExpression() . ' = ?',
[$filters['expense_category']],
);
}
if (($filters['second_level'] ?? '') !== '') {
$query->whereRaw(
$this->secondLevelExpression() . ' = ?',
[$filters['second_level']],
);
}
if (($filters['third_level'] ?? '') !== '') {
$query->whereRaw(
$this->thirdLevelExpression() . ' = ?',
[$filters['third_level']],
);
}
if (($filters['allocation'] ?? '') !== '') {
$query->whereRaw(
$this->allocationExpression() . ' = ?',
[$filters['allocation']],
);
}
if (($filters['fee_ratio'] ?? '') === 'in') {
$query->where('m.in_fee_ratio', 1);
} elseif (($filters['fee_ratio'] ?? '') === 'out') {
$query->where('m.in_fee_ratio', 0);
} elseif (($filters['fee_ratio'] ?? '') === 'unmapped') {
$query->whereNull('m.account_code');
}
foreach ([
'business_id' => 'd.business_id',
'originator_department' => 'd.originator_department',
'originator_name' => 'd.originator_name',
'keyword' => 'd.purpose',
] as $filter => $column) {
$value = trim((string) ($filters[$filter] ?? ''));
if ($value !== '') {
$query->where($column, 'like', '%' . $value . '%');
}
}
return $query;
}
private function amountSplitExpression(): string
{
return 'COUNT(*) AS row_count, '
. 'COUNT(DISTINCT d.business_id) AS approval_count, '
. 'SUM(COALESCE(d.amount, 0)) AS amount_total, '
. 'SUM(CASE WHEN m.in_fee_ratio = 1 THEN COALESCE(d.amount, 0) ELSE 0 END) AS in_fee_ratio_amount, '
. 'SUM(CASE WHEN m.account_code IS NOT NULL AND m.in_fee_ratio = 0 '
. 'THEN COALESCE(d.amount, 0) ELSE 0 END) AS non_fee_ratio_amount, '
. 'SUM(CASE WHEN m.account_code IS NULL THEN COALESCE(d.amount, 0) ELSE 0 END) AS unmapped_amount';
}
private function categoryExpression(): string
{
return "COALESCE(NULLIF(m.expense_category, ''), '未映射科目')";
}
private function secondLevelExpression(): string
{
return "COALESCE(NULLIF(m.second_level, ''), '未映射科目')";
}
private function thirdLevelExpression(): string
{
return "COALESCE(NULLIF(m.third_level, ''), '未细分')";
}
private function feeRatioExpression(): string
{
return "CASE WHEN m.account_code IS NULL THEN '未映射科目' "
. "WHEN m.in_fee_ratio = 1 THEN '进费比' ELSE '不进费比' END";
}
private function allocationExpression(): string
{
return "COALESCE(NULLIF(m.allocation, ''), '未标注')";
}
private function groupKey(string $category, string $secondLevel): string
{
return sha1($category . "\0" . $secondLevel);
}
/** @return array<string,list<string>> */
private function options(): array
{
$table = $this->connection->table('oa_process_account_mapping');
$categories = (clone $table)
->distinct()
->orderBy('expense_category')
->pluck('expense_category')
->map(static fn (mixed $value): string => (string) $value)
->values()
->all();
$secondLevels = (clone $table)
->distinct()
->orderBy('second_level')
->pluck('second_level')
->map(static fn (mixed $value): string => (string) $value)
->values()
->all();
$thirdLevels = (clone $table)
->distinct()
->orderBy('third_level')
->pluck('third_level')
->map(static fn (mixed $value): string => (string) $value)
->values()
->all();
$allocations = (clone $table)
->whereNotNull('allocation')
->where('allocation', '<>', '')
->distinct()
->orderBy('allocation')
->pluck('allocation')
->map(static fn (mixed $value): string => (string) $value)
->values()
->all();
$categories[] = '未映射科目';
$secondLevels[] = '未映射科目';
$thirdLevels[] = '未映射科目';
$allocations[] = '未标注';
$categories = $this->sortOptions($categories);
$secondLevels = $this->sortOptions($secondLevels);
$thirdLevels = $this->sortOptions($thirdLevels);
$allocations = $this->sortOptions($allocations);
return [
'categories' => $categories,
'second_levels' => $secondLevels,
'third_levels' => $thirdLevels,
'allocations' => $allocations,
'fee_ratios' => self::FEE_RATIO_OPTIONS,
];
}
/** @return list<string> */
private function sortOptions(array $values): array
{
$values = array_values(array_unique(array_filter(
$values,
static fn (string $value): bool => $value !== '',
)));
sort($values, SORT_NATURAL | SORT_FLAG_CASE);
return $values;
}
/** @return array<string,list<string>|array<string,string>> */
private function emptyOptions(): array
{
return [
'categories' => [],
'second_levels' => [],
'third_levels' => [],
'allocations' => [],
'fee_ratios' => self::FEE_RATIO_OPTIONS,
];
}
/** @return array<string,int|float> */
private function emptySummary(): array
{
return [
'amount_total' => 0.0,
'in_fee_ratio_amount' => 0.0,
'non_fee_ratio_amount' => 0.0,
'unmapped_amount' => 0.0,
'row_count' => 0,
'approval_count' => 0,
];
}
/** @return array{0:string,1:string} */
private static function dateRange(mixed $start, mixed $end): array
{
$normalize = static function (mixed $value): string {
$date = trim((string) $value);
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date, $parts) !== 1
|| ! checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1])) {
return '';
}
return $date;
};
$start = $normalize($start);
$end = $normalize($end);
if ($start !== '' && $end !== '' && $start > $end) {
[$start, $end] = [$end, $start];
}
return [$start, $end];
}
private static function perPage(mixed $value): int
{
$perPage = (int) $value;
return in_array($perPage, self::PER_PAGE_OPTIONS, true)
? $perPage
: self::DEFAULT_PER_PAGE;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -24,6 +24,7 @@ use Modules\EcommerceFinance\Http\Controllers\AlipayBills;
use Modules\EcommerceFinance\Http\Controllers\DewuAccountBills;
use Modules\EcommerceFinance\Http\Controllers\PinduoduoAccountBills;
use Modules\EcommerceFinance\Http\Controllers\TaobaoWechatAccountBills;
use Modules\EcommerceFinance\Http\Controllers\ManagementExpenses;
use Modules\EcommerceFinance\Http\Controllers\Api\GoodsReconciliations;
use Modules\EcommerceFinance\Http\Controllers\Api\SupplierPayables;
use Modules\EcommerceFinance\Http\Controllers\ThirdPartyWarehouseStorageSettlementExportController;
@ -638,6 +639,13 @@ Route::get('workspace/financial-operations/expense-details/item-summary', 'Busin
->middleware('business.page:financial-operations,expense-details')
->name('business.financial-operations.expense-details.item-summary');
Route::get(
'workspace/financial-operations/management-expenses/details',
[ManagementExpenses::class, 'details'],
)
->middleware('business.page:financial-operations,management-expenses')
->name('business.financial-operations.management-expenses.details');
Route::get('workspace/financial-operations/billing-details/export', 'Business\Pages@exportBillingDetails')
->middleware('business.page:financial-operations,billing-details')
->name('business.financial-operations.billing-details.export');

View File

@ -0,0 +1,118 @@
<?php
namespace Tests\Feature\Business;
use App\Models\Auth\Permission;
use Illuminate\Pagination\LengthAwarePaginator;
use Mockery;
use Modules\EcommerceFinance\View\ManagementExpensesPageData;
use Tests\Feature\FeatureTestCase;
class ManagementExpensesPageTest extends FeatureTestCase
{
public function test_page_renders_second_level_summary_and_detail_template(): void
{
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$service = Mockery::mock(ManagementExpensesPageData::class);
$service->shouldReceive('page')->once()->andReturn([
'view' => 'business.pages.financial-operations.management-expenses',
'pageTitle' => '管理费用',
'rows' => new LengthAwarePaginator([
[
'business_id' => '202610301323000477793',
'originator_department' => '财务中心',
'purpose' => '测试用途',
'expense_category' => '管理费用',
'second_level' => '办公费',
'third_level' => '办公费用品',
'amount' => 100.0,
'fee_ratio' => '不进费比',
'allocation' => '分摊',
],
], 1, 50, 1),
'filters' => [
'paid_start' => '', 'paid_end' => '', 'expense_category' => '',
'second_level' => '', 'third_level' => '', 'fee_ratio' => '',
'allocation' => '', 'business_id' => '', 'originator_department' => '',
'originator_name' => '', 'keyword' => '',
],
'summary' => [
'amount_total' => 100.0, 'in_fee_ratio_amount' => 0.0,
'non_fee_ratio_amount' => 100.0, 'unmapped_amount' => 0.0,
'row_count' => 1, 'approval_count' => 1,
],
'secondLevelSummary' => [[
'expense_category' => '管理费用', 'second_level' => '办公费',
'in_fee_ratio_amount' => 0.0, 'non_fee_ratio_amount' => 100.0,
'unmapped_amount' => 0.0, 'amount_total' => 100.0,
'row_count' => 1, 'approval_count' => 1,
]],
'thirdLevelSummary' => [[
'expense_category' => '管理费用', 'second_level' => '办公费',
'third_level' => '办公费用品', 'in_fee_ratio_amount' => 0.0,
'non_fee_ratio_amount' => 100.0, 'unmapped_amount' => 0.0,
'amount_total' => 100.0, 'row_count' => 1, 'approval_count' => 1,
]],
'options' => [
'categories' => ['管理费用'], 'second_levels' => ['办公费'],
'third_levels' => ['办公费用品'], 'allocations' => ['分摊'],
'fee_ratios' => ManagementExpensesPageData::FEE_RATIO_OPTIONS,
],
'perPageOptions' => ManagementExpensesPageData::PER_PAGE_OPTIONS,
'detailColumns' => ManagementExpensesPageData::DETAIL_COLUMNS,
'detailsUrl' => route(
'business.financial-operations.management-expenses.details',
['company_id' => company_id() ?: 1],
),
'error' => null,
]);
$this->app->instance(ManagementExpensesPageData::class, $service);
$this->loginAs()->get(route('business.pages.show', [
'section' => 'financial-operations',
'page' => 'management-expenses',
]))->assertOk()
->assertSee('管理费用')
->assertSee('二级汇总')
->assertSee('OA 已付款明细模板')
->assertSee('进费比')
->assertSee('不进费比')
->assertSee('是否分摊')
->assertSee('办公费用品')
->assertSee('202610301323000477793')
->assertSee('data-me-open-group', false);
}
public function test_details_endpoint_returns_template_rows(): void
{
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$service = Mockery::mock(ManagementExpensesPageData::class);
$service->shouldReceive('details')->once()->andReturn([
'rows' => [[
'business_id' => '202610301323000477793',
'originator_department' => '财务中心',
'purpose' => '测试用途',
'expense_category' => '管理费用',
'second_level' => '办公费',
'third_level' => '办公费用品',
'amount' => 100.0,
'fee_ratio' => '不进费比',
'allocation' => '分摊',
]],
'pagination' => ['current_page' => 1, 'last_page' => 1, 'per_page' => 50, 'total' => 1],
'summary' => [
'amount_total' => 100.0, 'in_fee_ratio_amount' => 0.0,
'non_fee_ratio_amount' => 100.0, 'unmapped_amount' => 0.0,
'row_count' => 1, 'approval_count' => 1,
],
]);
$this->app->instance(ManagementExpensesPageData::class, $service);
$this->loginAs()->getJson(route('business.financial-operations.management-expenses.details'))
->assertOk()
->assertJsonPath('success', true)
->assertJsonPath('rows.0.business_id', '202610301323000477793')
->assertJsonPath('rows.0.fee_ratio', '不进费比')
->assertJsonPath('pagination.total', 1);
}
}

View File

@ -0,0 +1,218 @@
<?php
namespace Tests\Unit\EcommerceFinance;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\View\ManagementExpensesPageData;
use Tests\TestCase;
class ManagementExpensesPageDataTest extends TestCase
{
private ManagementExpensesPageData $pageData;
protected function setUp(): void
{
parent::setUp();
config([
'database.connections.business_mirror' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
'upstream_mirrors.connection' => 'business_mirror',
]);
DB::purge('business_mirror');
$this->createTables();
$this->seedRows();
$this->pageData = app(ManagementExpensesPageData::class);
}
public function test_page_groups_only_paid_oa_rows_by_second_level_and_fee_ratio(): void
{
$data = $this->pageData->page(Request::create(
'/1/workspace/financial-operations/management-expenses',
'GET',
));
$this->assertSame(5, $data['rows']->total());
$this->assertSame(675.0, $data['summary']['amount_total']);
$this->assertSame(500.0, $data['summary']['in_fee_ratio_amount']);
$this->assertSame(125.0, $data['summary']['non_fee_ratio_amount']);
$this->assertSame(50.0, $data['summary']['unmapped_amount']);
$this->assertSame(5, $data['summary']['row_count']);
$groups = collect($data['secondLevelSummary'])->keyBy(
static fn (array $row): string => $row['expense_category'] . '|' . $row['second_level'],
);
$this->assertSame(125.0, $groups['管理费用|办公费']['amount_total']);
$this->assertSame(1, $groups['管理费用|办公费']['approval_count']);
$this->assertSame(500.0, $groups['销售费用|技术服务费']['in_fee_ratio_amount']);
$this->assertSame(50.0, $groups['未映射科目|未映射科目']['unmapped_amount']);
$this->assertCount(3, $data['secondLevelSummary']);
}
public function test_detail_template_filters_and_paginates_paid_rows(): void
{
$data = $this->pageData->details(Request::create(
'/1/workspace/financial-operations/management-expenses/details',
'GET',
[
'expense_category' => '管理费用',
'second_level' => '办公费',
'per_page' => 50,
],
));
$this->assertSame(2, $data['pagination']['total']);
$this->assertSame(125.0, $data['summary']['amount_total']);
$this->assertSame(
['审批编号', '部门', '用途', '分类', '二级', '三级', '金额', '是否进费比', '是否分摊'],
array_values(ManagementExpensesPageData::DETAIL_COLUMNS),
);
$this->assertSame(
['5602.04', '5602.04'],
array_column($data['rows'], 'business_id'),
);
$this->assertSame('不进费比', $data['rows'][0]['fee_ratio']);
$this->assertSame('分摊', $data['rows'][0]['allocation']);
}
public function test_unmapped_account_is_visible_instead_of_being_silently_dropped(): void
{
$data = $this->pageData->details(Request::create(
'/1/workspace/financial-operations/management-expenses/details',
'GET',
['fee_ratio' => 'unmapped'],
));
$this->assertSame(1, $data['pagination']['total']);
$this->assertSame('未映射科目', $data['rows'][0]['expense_category']);
$this->assertSame(50.0, $data['rows'][0]['amount']);
}
public function test_workbook_mapping_snapshot_is_complete_and_unique(): void
{
$mapping = json_decode(
(string) file_get_contents(base_path('resources/data/oa_process_account_mapping.json')),
true,
512,
JSON_THROW_ON_ERROR,
);
$this->assertCount(191, $mapping);
$this->assertCount(191, array_unique(array_column($mapping, 'account_code')));
$this->assertSame(33, count(array_filter($mapping, static fn (array $row): bool => $row['in_fee_ratio'])));
$this->assertSame(125, count(array_filter($mapping, static fn (array $row): bool => $row['allocation'] !== null)));
$this->assertContains('分摊', array_column($mapping, 'allocation'));
$this->assertContains('核实进店铺', array_column($mapping, 'allocation'));
$this->assertContains('进店铺', array_column($mapping, 'allocation'));
}
private function createTables(): void
{
Schema::connection('business_mirror')->create(
'oa_process_account_mapping',
function (Blueprint $table): void {
$table->string('account_code', 64)->primary();
$table->string('account_name', 255);
$table->string('expense_category', 100);
$table->string('second_level', 100);
$table->string('third_level', 100);
$table->boolean('in_fee_ratio')->default(false);
$table->string('allocation', 100)->nullable();
$table->timestamps();
},
);
Schema::connection('business_mirror')->create(
'ding_process_detail_mirror',
function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('business_id', 32);
$table->string('process_instance_id', 100)->nullable();
$table->unsignedInteger('line_no');
$table->string('account_code', 64)->nullable();
$table->string('account_name', 255)->nullable();
$table->string('originator_department', 255)->nullable();
$table->string('originator_name', 100)->nullable();
$table->string('status', 20)->nullable();
$table->string('payment_source_state', 24)->nullable();
$table->string('cashier_status', 32)->nullable();
$table->text('purpose')->nullable();
$table->decimal('amount', 18, 2)->nullable();
$table->string('paid_at', 50)->nullable();
$table->timestamps();
},
);
}
private function seedRows(): void
{
$now = now();
DB::connection('business_mirror')->table('oa_process_account_mapping')->insert([
[
'account_code' => '5602.04',
'account_name' => '管理费用_办公费',
'expense_category' => '管理费用',
'second_level' => '办公费',
'third_level' => '办公费用品',
'in_fee_ratio' => false,
'allocation' => '分摊',
'created_at' => $now,
'updated_at' => $now,
],
[
'account_code' => '5601.05.03',
'account_name' => '销售费用_营销费用_软件服务费',
'expense_category' => '销售费用',
'second_level' => '技术服务费',
'third_level' => '软件服务费',
'in_fee_ratio' => true,
'allocation' => null,
'created_at' => $now,
'updated_at' => $now,
],
]);
DB::connection('business_mirror')->table('ding_process_detail_mirror')->insert([
$this->row('5602.04', 1, 100, '已完成', 'completed', 'present', '2026-10-01'),
$this->row('5601.05.03', 1, 200, '已完成', 'completed', 'present', '2026-10-02'),
$this->row('5601.05.03', 1, 300, '审批中', 'completed', 'present', '2026-10-03'),
$this->row('5602.04', 1, 400, '审批中', 'pending', 'present', '2026-10-04'),
$this->row('9999.99', 1, 50, '已完成', 'completed', 'present', '2026-10-05'),
$this->row('5601.05.03', 1, 70, '已完成', 'not_applicable', 'not_applicable', '2026-10-06'),
$this->row('5602.04', 1, 25, '已完成', null, 'present', '2026-10-07'),
]);
}
/** @return array<string,mixed> */
private function row(
string $businessId,
int $lineNo,
float $amount,
string $status,
?string $cashierStatus,
string $paymentSourceState,
string $paidAt,
): array {
return [
'business_id' => $businessId,
'process_instance_id' => 'process-' . $businessId,
'line_no' => $lineNo,
'account_code' => $businessId,
'account_name' => '流程科目',
'originator_department' => '财务中心',
'originator_name' => '测试申请人',
'status' => $status,
'payment_source_state' => $paymentSourceState,
'cashier_status' => $cashierStatus,
'purpose' => '测试用途',
'amount' => $amount,
'paid_at' => $paidAt,
'created_at' => now(),
'updated_at' => now(),
];
}
}