diff --git a/app/Business/JstOrderLabelDailySynchronizer.php b/app/Business/JstOrderLabelDailySynchronizer.php new file mode 100644 index 00000000..017175ed --- /dev/null +++ b/app/Business/JstOrderLabelDailySynchronizer.php @@ -0,0 +1,322 @@ + + */ + public function sync( + string $from, + string $to, + int $companyId, + int $refreshDays = 7, + bool $dryRun = false, + ): array { + [$fromDate, $toDate] = $this->dateRange($from, $to); + if ($companyId <= 0) { + throw new InvalidArgumentException('公司 ID 无效。'); + } + if ($refreshDays < 1 || $refreshDays > 31) { + throw new InvalidArgumentException('刷新天数必须在 1 至 31 之间。'); + } + + $this->assertSourceReady(); + + $refreshStart = $fromDate->copy(); + $candidateRefreshStart = $toDate->copy()->subDays($refreshDays - 1); + if ($candidateRefreshStart->gt($refreshStart)) { + $refreshStart = $candidateRefreshStart; + } + + $historyEnd = $refreshStart->copy()->subDay(); + $historyCoverage = $historyEnd->lt($fromDate) + ? [] + : $this->coverage($fromDate, $historyEnd, $companyId); + $historyIssues = array_values(array_filter( + $historyCoverage, + static fn (array $row): bool => $row['status'] !== 'ok', + )); + + foreach ($historyIssues as $issue) { + if ($issue['status'] === 'source_empty') { + throw new RuntimeException(sprintf( + '历史数据检查未通过:源订单镜像在 %s 没有订单,已停止拉取新数据。', + $issue['date'], + )); + } + } + + $backfills = $this->contiguousRanges($historyIssues); + if ($dryRun) { + return [ + 'status' => $historyIssues === [] ? 'would_refresh' : 'would_backfill', + 'from' => $fromDate->toDateString(), + 'to' => $toDate->toDateString(), + 'checked_days' => (int) $fromDate->diffInDays($toDate) + 1, + 'history_issues' => $historyIssues, + 'backfills' => array_map(static fn (array $range): array => [ + 'from' => $range['from'], + 'to' => $range['to'], + ], $backfills), + 'refresh' => [ + 'from' => $refreshStart->toDateString(), + 'to' => $toDate->toDateString(), + ], + ]; + } + + $backfillResults = []; + foreach ($backfills as $range) { + $backfillResults[] = $this->importer->import( + $range['from'], + $range['to'], + $companyId, + true, + 'jst-order-label-daily-sync', + ); + } + + if ($historyIssues !== []) { + $remainingHistory = $this->coverage($fromDate, $historyEnd, $companyId); + $remainingIssues = array_values(array_filter( + $remainingHistory, + static fn (array $row): bool => $row['status'] !== 'ok', + )); + if ($remainingIssues !== []) { + throw new RuntimeException('历史缺口补导后仍未通过覆盖检查:' . $this->issueSummary($remainingIssues)); + } + } + + $refreshResult = $this->importer->import( + $refreshStart->toDateString(), + $toDate->toDateString(), + $companyId, + true, + 'jst-order-label-daily-sync', + ); + + $finalCoverage = $this->coverage($fromDate, $toDate, $companyId); + $finalIssues = array_values(array_filter( + $finalCoverage, + static fn (array $row): bool => $row['status'] !== 'ok', + )); + if ($finalIssues !== []) { + throw new RuntimeException('同步后覆盖检查未通过:' . $this->issueSummary($finalIssues)); + } + + return [ + 'status' => 'ok', + 'from' => $fromDate->toDateString(), + 'to' => $toDate->toDateString(), + 'checked_days' => count($finalCoverage), + 'backfilled_ranges' => array_map(static fn (array $range): array => [ + 'from' => $range['from'], + 'to' => $range['to'], + ], $backfills), + 'backfill_results' => $backfillResults, + 'refresh' => $refreshResult, + ]; + } + + /** + * 只读确认指定日期都已覆盖;任何缺日或订单数不一致都会阻止下游重算。 + * + * @return list + */ + public function assertCovered(string $from, string $to, int $companyId): array + { + [$fromDate, $toDate] = $this->dateRange($from, $to); + if ($companyId <= 0) { + throw new InvalidArgumentException('公司 ID 无效。'); + } + + $this->assertSourceReady(); + $coverage = $this->coverage($fromDate, $toDate, $companyId); + $issues = array_values(array_filter( + $coverage, + static fn (array $row): bool => $row['status'] !== 'ok', + )); + if ($issues !== []) { + throw new RuntimeException('历史数据检查未通过:' . $this->issueSummary($issues)); + } + + return $coverage; + } + + /** + * 逐日比较源订单号数与标签明细订单号数。 + * + * 标签拆行后同一订单会出现多行,因此不能用总行数直接比较订单完整性。 + * + * @return list + */ + public function coverage(Carbon $from, Carbon $to, int $companyId): array + { + $start = $from->copy()->startOfDay()->toDateTimeString(); + $end = $to->copy()->addDay()->startOfDay()->toDateTimeString(); + $mirror = $this->mirror(); + $target = $this->databases->connection(); + + $sourceRows = $mirror->table('ops_jst_orders') + ->where('order_date', '>=', $start) + ->where('order_date', '<', $end) + ->selectRaw('DATE(order_date) AS day, COUNT(DISTINCT so_id) AS order_count') + ->groupByRaw('DATE(order_date)') + ->get() + ->keyBy('day'); + + $targetRows = $target->table('jst_order_labels') + ->where('company_id', $companyId) + ->where('ordered_at', '>=', $start) + ->where('ordered_at', '<', $end) + ->selectRaw('DATE(ordered_at) AS day, COUNT(*) AS row_count, COUNT(DISTINCT order_no) AS order_count') + ->groupByRaw('DATE(ordered_at)') + ->get() + ->keyBy('day'); + + $coverage = []; + for ($day = $from->copy()->startOfDay(); $day->lte($to); $day->addDay()) { + $date = $day->toDateString(); + $sourceOrders = (int) ($sourceRows[$date]->order_count ?? 0); + $targetOrderCount = (int) ($targetRows[$date]->order_count ?? 0); + $targetRowsCount = (int) ($targetRows[$date]->row_count ?? 0); + $status = match (true) { + $sourceOrders === 0 => 'source_empty', + $targetOrderCount === 0 => 'missing', + $targetOrderCount < $sourceOrders => 'incomplete', + $targetOrderCount > $sourceOrders => 'extra_orders', + default => 'ok', + }; + + $coverage[] = [ + 'date' => $date, + 'source_orders' => $sourceOrders, + 'target_orders' => $targetOrderCount, + 'target_rows' => $targetRowsCount, + 'status' => $status, + ]; + } + + return $coverage; + } + + private function assertSourceReady(): void + { + $mirror = $this->mirror(); + $schema = $mirror->getSchemaBuilder(); + if (! $schema->hasTable('ops_jst_orders')) { + throw new RuntimeException('聚水潭订单镜像尚未建立(ops_jst_orders)。'); + } + if (! $schema->hasTable('business_mirror_table_states')) { + throw new RuntimeException('聚水潭订单镜像同步状态表尚未建立。'); + } + + $state = $mirror->table('business_mirror_table_states') + ->where('dataset_key', self::SOURCE_DATASET) + ->first(['status', 'initial_completed_at']); + if ($state === null || $state->initial_completed_at === null) { + throw new RuntimeException('聚水潭订单镜像尚未完成首次同步。'); + } + if ((string) $state->status !== 'succeeded') { + throw new RuntimeException('聚水潭订单镜像最近同步未成功,已停止标签明细同步。'); + } + } + + private function mirror(): \Illuminate\Database\ConnectionInterface + { + return $this->databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @param list $issues + * @return list + */ + private function contiguousRanges(array $issues): array + { + usort($issues, static fn (array $left, array $right): int => $left['date'] <=> $right['date']); + $ranges = []; + $start = null; + $previous = null; + + foreach ($issues as $issue) { + $day = Carbon::createFromFormat('!Y-m-d', $issue['date'], 'Asia/Shanghai'); + if ($start === null) { + $start = $day; + $previous = $day; + continue; + } + + if (! $day->isSameDay($previous->copy()->addDay())) { + $ranges[] = ['from' => $start->toDateString(), 'to' => $previous->toDateString()]; + $start = $day; + } + $previous = $day; + } + + if ($start !== null && $previous !== null) { + $ranges[] = ['from' => $start->toDateString(), 'to' => $previous->toDateString()]; + } + + return $ranges; + } + + /** @param list $issues */ + private function issueSummary(array $issues): string + { + return implode(',', array_map( + static fn (array $issue): string => $issue['date'] . '=' . $issue['status'], + $issues, + )); + } + + /** @return array{0:Carbon,1:Carbon} */ + private function dateRange(string $from, string $to): array + { + $fromDate = $this->date($from); + $toDate = $this->date($to); + if ($fromDate === null || $toDate === null || $fromDate->gt($toDate)) { + throw new InvalidArgumentException('日期范围无效,应为 from <= to,格式 YYYY-MM-DD。'); + } + + return [$fromDate, $toDate]; + } + + private function date(string $value): ?Carbon + { + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) { + return null; + } + + try { + $date = Carbon::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai'); + } catch (Throwable) { + return null; + } + + return $date->format('Y-m-d') === $value ? $date : null; + } +} diff --git a/app/Business/StoreReceiptPlantingDailySynchronizer.php b/app/Business/StoreReceiptPlantingDailySynchronizer.php new file mode 100644 index 00000000..479635c9 --- /dev/null +++ b/app/Business/StoreReceiptPlantingDailySynchronizer.php @@ -0,0 +1,165 @@ + $months + * @return array + */ + public function sync( + string $from, + string $to, + int $companyId, + array $months = [], + bool $dryRun = false, + ): array { + [$fromDate, $toDate] = $this->dateRange($from, $to); + if ($companyId <= 0) { + throw new InvalidArgumentException('公司 ID 无效。'); + } + + $coverage = $this->labelCoverage->assertCovered( + $fromDate->toDateString(), + $toDate->toDateString(), + $companyId, + ); + $months = $this->months($months, $toDate); + $this->assertWorkOrderSourceReady(); + + if ($dryRun) { + return [ + 'status' => 'ready', + 'from' => $fromDate->toDateString(), + 'to' => $toDate->toDateString(), + 'checked_days' => count($coverage), + 'months' => $months, + 'dry_run' => true, + ]; + } + + $plantingSync = []; + foreach ($months as $month) { + $plantingSync[$month] = $this->plantingWorkOrders->sync( + $month . '-01', + $this->monthEnd($month), + $companyId, + ); + } + + return [ + 'status' => 'ready_to_refresh', + 'from' => $fromDate->toDateString(), + 'to' => $toDate->toDateString(), + 'checked_days' => count($coverage), + 'months' => $months, + 'planting_sync' => $plantingSync, + 'dry_run' => false, + ]; + } + + /** @return list */ + private function months(array $requested, Carbon $through): array + { + if ($requested === []) { + return [ + $through->copy()->subMonthNoOverflow()->format('Y-m'), + $through->format('Y-m'), + ]; + } + + $months = []; + foreach ($requested as $month) { + $month = trim((string) $month); + $normalized = null; + if (preg_match('/^\d{4}-\d{2}$/', $month) === 1) { + try { + $normalized = Carbon::createFromFormat('!Y-m', $month, 'Asia/Shanghai')->format('Y-m'); + } catch (Throwable) { + $normalized = null; + } + } + if ($normalized !== $month) { + throw new InvalidArgumentException('月份格式无效,应为 YYYY-MM:' . $month); + } + $months[$month] = true; + } + $months = array_keys($months); + sort($months); + + return $months; + } + + private function assertWorkOrderSourceReady(): void + { + $mirror = $this->databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + $schema = $mirror->getSchemaBuilder(); + if (! $schema->hasTable('business_mirror_table_states')) { + throw new RuntimeException('聚水潭协同工单镜像同步状态表尚未建立。'); + } + + $state = $mirror->table('business_mirror_table_states') + ->where('dataset_key', self::WORK_ORDER_DATASET) + ->first(['status', 'initial_completed_at']); + if ($state === null || $state->initial_completed_at === null) { + throw new RuntimeException('聚水潭协同工单镜像尚未完成首次同步。'); + } + if ((string) $state->status !== 'succeeded') { + throw new RuntimeException('聚水潭协同工单镜像最近同步未成功。'); + } + } + + /** @return array{0:Carbon,1:Carbon} */ + private function dateRange(string $from, string $to): array + { + $fromDate = $this->date($from); + $toDate = $this->date($to); + if ($fromDate === null || $toDate === null || $fromDate->gt($toDate)) { + throw new InvalidArgumentException('日期范围无效,应为 from <= to,格式 YYYY-MM-DD。'); + } + + return [$fromDate, $toDate]; + } + + private function date(string $value): ?Carbon + { + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) { + return null; + } + + try { + $date = Carbon::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai'); + } catch (Throwable) { + return null; + } + + return $date->format('Y-m-d') === $value ? $date : null; + } + + private function monthEnd(string $month): string + { + return Carbon::createFromFormat('!Y-m', $month, 'Asia/Shanghai') + ->endOfMonth() + ->toDateString(); + } +} diff --git a/app/Console/Commands/SyncDingWorklogs.php b/app/Console/Commands/SyncDingWorklogs.php index 268e0043..c8f47818 100644 --- a/app/Console/Commands/SyncDingWorklogs.php +++ b/app/Console/Commands/SyncDingWorklogs.php @@ -2,6 +2,7 @@ namespace App\Console\Commands; +use App\Services\Auth\FinanceRoster; use Illuminate\Console\Command; use Modules\EcommerceFinance\Exceptions\DingTalkWorklogException; use Modules\EcommerceFinance\Repositories\DingWorklogMirrorRepository; @@ -19,6 +20,7 @@ class SyncDingWorklogs extends Command public function handle( DingTalkWorklogClient $client, DingWorklogMirrorRepository $repository, + FinanceRoster $financeRoster, ): int { if (! (bool) config('dingtalk.worklog.enabled', true)) { return self::SUCCESS; @@ -36,17 +38,47 @@ class SyncDingWorklogs extends Command } $days = max((int) ($this->option('days') ?: config('dingtalk.worklog.lookback_days', 35)), 1); - $template = trim((string) ($this->option('template') ?: config('dingtalk.worklog.template_name', '财务日报'))); + $templates = $this->templates(); $to = now(); $from = $to->copy()->subDays($days)->startOfDay(); try { - $result = $client->listReports($from, $to, $template); $now = now(); + $pages = 0; + $reports = []; + foreach ($templates as $template) { + $result = $client->listReports($from, $to, $template); + $pages += (int) $result['pages']; + foreach ($result['reports'] as $report) { + if (! is_array($report)) { + continue; + } + $reportId = DingWorklogMirrorRepository::reportId($report); + $reports[$reportId] = [ + 'requested_template' => $template, + 'report' => $report, + ]; + } + } + + $financeOnlyTemplates = array_values(array_filter(array_map( + 'trim', + (array) config('dingtalk.worklog.finance_only_templates', ['空白日志']), + ))); + $financeMembers = null; $rows = []; - foreach ($result['reports'] as $report) { - if (! is_array($report)) { - continue; + foreach ($reports as $reportId => $entry) { + $report = $entry['report']; + $templateName = trim((string) ($report['template_name'] ?? $entry['requested_template'])); + $creatorUserId = mb_substr(trim((string) ($report['creator_userid'] ?? $report['creator_id'] ?? '')), 0, 128); + if (in_array($templateName, $financeOnlyTemplates, true)) { + $financeMembers ??= array_fill_keys( + array_column($financeRoster->cachedFinanceMembers(), 'userid'), + true, + ); + if (! isset($financeMembers[$creatorUserId])) { + continue; + } } $submittedRaw = $report['create_time'] ?? $report['created_at'] @@ -63,9 +95,9 @@ class SyncDingWorklogs extends Command } $statisticsDate = DingWorklogMirrorRepository::statisticsDate($submittedAt); $rows[] = [ - 'report_id' => DingWorklogMirrorRepository::reportId($report), - 'template_name' => mb_substr(trim((string) ($report['template_name'] ?? $template)), 0, 191), - 'creator_userid' => mb_substr(trim((string) ($report['creator_userid'] ?? $report['creator_id'] ?? '')), 0, 128), + 'report_id' => $reportId, + 'template_name' => mb_substr($templateName, 0, 191), + 'creator_userid' => $creatorUserId, 'creator_name' => mb_substr(trim((string) ($report['creator_name'] ?? $report['creator_nick'] ?? '')), 0, 191), 'submitted_at' => $submittedAt->toDateTimeString(), 'statistics_date' => $statisticsDate->toDateString(), @@ -78,11 +110,11 @@ class SyncDingWorklogs extends Command } $upserted = $repository->upsertReports($rows); - $repository->recordSuccess($upserted, $template, $from, $to); + $repository->recordSuccess($upserted, implode(' / ', $templates), $from, $to); $this->info(sprintf( '钉钉日志同步完成:读取 %d 页,写入/更新 %d 条。', - $result['pages'], + $pages, $upserted, )); @@ -101,4 +133,22 @@ class SyncDingWorklogs extends Command return self::FAILURE; } } + + /** @return list */ + private function templates(): array + { + $configured = trim((string) $this->option('template')); + $templates = $configured !== '' + ? preg_split('/[,,]/u', $configured, -1, PREG_SPLIT_NO_EMPTY) + : (array) config('dingtalk.worklog.template_names', [ + config('dingtalk.worklog.template_name', '财务日报'), + ]); + $templates = array_values(array_unique(array_filter(array_map( + static fn (mixed $template): string => trim((string) $template), + $templates, + )))); + + return $templates !== [] ? $templates : ['财务日报']; + } + } diff --git a/app/Console/Commands/SyncJstOrderLabelsDaily.php b/app/Console/Commands/SyncJstOrderLabelsDaily.php new file mode 100644 index 00000000..551c626f --- /dev/null +++ b/app/Console/Commands/SyncJstOrderLabelsDaily.php @@ -0,0 +1,84 @@ +option('from')); + $to = trim((string) $this->option('to')); + $to = $to !== '' ? $to : Carbon::now('Asia/Shanghai')->subDay()->toDateString(); + + try { + $result = $synchronizer->sync( + $from, + $to, + (int) $this->option('company'), + (int) $this->option('refresh-days'), + (bool) $this->option('dry-run'), + ); + } catch (Throwable $exception) { + if ($this->option('json')) { + $this->line(json_encode([ + 'status' => 'failed', + 'from' => $from, + 'to' => $to, + 'error' => $exception->getMessage(), + ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + } else { + $this->error($exception->getMessage()); + } + + return self::FAILURE; + } + + if ($this->option('json')) { + $this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + return self::SUCCESS; + } + + $this->info(sprintf( + '聚水潭订单标签明细同步完成:%s ~ %s,覆盖 %d 天。', + $result['from'], + $result['to'], + (int) ($result['checked_days'] ?? 0), + )); + foreach ($result['backfill_results'] ?? [] as $backfill) { + $this->line(sprintf( + ' 补导 %s ~ %s:%d 单,%d 行。', + $backfill['from'], + $backfill['to'], + (int) $backfill['orders'], + (int) $backfill['rows'], + )); + } + $refresh = $result['refresh'] ?? null; + if (is_array($refresh)) { + $this->line(sprintf( + ' 刷新 %s ~ %s:%d 单,%d 行。', + $refresh['from'], + $refresh['to'], + (int) $refresh['orders'], + (int) $refresh['rows'], + )); + } + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/SyncStoreReceiptPlantingDaily.php b/app/Console/Commands/SyncStoreReceiptPlantingDaily.php new file mode 100644 index 00000000..ef34997d --- /dev/null +++ b/app/Console/Commands/SyncStoreReceiptPlantingDaily.php @@ -0,0 +1,113 @@ +option('from')); + $to = trim((string) $this->option('to')); + $to = $to !== '' ? $to : Carbon::now('Asia/Shanghai')->subDay()->toDateString(); + $companyId = (int) $this->option('company'); + $months = array_values(array_filter( + array_map('strval', (array) $this->option('month')), + static fn (string $month): bool => trim($month) !== '', + )); + + try { + $result = $synchronizer->sync( + $from, + $to, + $companyId, + $months, + (bool) $this->option('dry-run'), + ); + } catch (Throwable $exception) { + $this->outputResult([ + 'status' => 'failed', + 'from' => $from, + 'to' => $to, + 'error' => $exception->getMessage(), + ]); + + return self::FAILURE; + } + + if ((bool) $this->option('dry-run')) { + $this->outputResult($result); + return self::SUCCESS; + } + + $results = []; + foreach ($result['months'] as $month) { + $exitCode = $this->call('store-receipt:order-match:sync', [ + 'month' => $month, + '--company' => $companyId, + '--planting-only' => true, + ]); + $results[$month] = ['exit_code' => $exitCode]; + if ($exitCode !== self::SUCCESS) { + $this->outputResult([ + 'status' => 'failed', + 'from' => $from, + 'to' => $to, + 'months' => $result['months'], + 'results' => $results, + 'error' => $month . ' 种菜金额重算失败。', + ]); + + return self::FAILURE; + } + } + + $result['status'] = 'ok'; + $result['results'] = $results; + $this->outputResult($result); + + return self::SUCCESS; + } + + private function outputResult(array $result): void + { + if ((bool) $this->option('json')) { + $this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + return; + } + + if (($result['status'] ?? '') === 'failed') { + $this->error((string) ($result['error'] ?? '种菜金额同步失败。')); + return; + } + + $this->info(sprintf( + '业绩明细种菜金额已刷新:核查 %s ~ %s,月份 %s。', + $result['from'], + $result['to'], + implode('、', $result['months']), + )); + foreach ($result['planting_sync'] ?? [] as $month => $sync) { + $this->line(sprintf( + ' %s 种菜报销明细:%d 单,写入 %d 行。', + $month, + (int) ($sync['orders'] ?? 0), + (int) ($sync['inserted'] ?? 0), + )); + } + } +} diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 855166a6..63a0cd08 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -4168,8 +4168,12 @@ class Pages extends Controller })); } - // 货款/退货明细较宽,固定每页 15 行,减少纵向滚动并保持横向核对区稳定。 - $perPage = in_array($dataset, ['payment-reconciliation', 'return-reconciliation'], true) ? 15 : 50; + // 宽表固定每页 15 行,减少纵向滚动并保持横向核对区稳定。 + $perPage = in_array($dataset, [ + 'payment-reconciliation', + 'return-reconciliation', + 'supplier-payables-report', + ], true) ? 15 : 50; $currentPage = max((int) request('page', 1), 1); return [ diff --git a/app/Services/Auth/FinanceRoster.php b/app/Services/Auth/FinanceRoster.php index 3a0e32a0..190fe119 100644 --- a/app/Services/Auth/FinanceRoster.php +++ b/app/Services/Auth/FinanceRoster.php @@ -2,11 +2,14 @@ namespace App\Services\Auth; +use Illuminate\Support\Facades\Cache; use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory; /** Single-person, current HR authorization lookup; no HR rows or stale grants are cached. */ class FinanceRoster { + private const FINANCE_MEMBERS_CACHE_KEY = 'dingtalk:finance-members:v1'; + public static function isDesignatedSuperAdmin(string $userId): bool { return $userId !== '' && in_array($userId, config('dingtalk.super_admin_user_ids', []), true); @@ -101,6 +104,75 @@ class FinanceRoster ]; } + /** + * 当前财务中心在职人员,只用于日志应提交名单和统计口径。 + * + * @return list + */ + public function financeMembers(): array + { + $roots = array_values(array_filter( + array_map('strval', (array) config('dingtalk.finance_department_ids', [])), + static fn (string $id): bool => ctype_digit($id) && (int) $id > 0, + )); + if ($roots === []) { + return []; + } + + $placeholders = implode(',', array_fill(0, count($roots), '?')); + $sql = <<queries->forSourceWithTimeout('operations_replica', 60)->select($sql, $roots); + + return array_values(array_filter(array_map(static function (array $row): ?array { + $userId = trim((string) ($row['userid'] ?? '')); + $flowerName = trim((string) ($row['flowerName'] ?? '')); + $name = trim((string) ($row['name'] ?? '')); + if ($userId === '' || ($flowerName === '' && $name === '')) { + return null; + } + + return ['userid' => $userId, 'name' => $flowerName !== '' ? $flowerName : $name]; + }, $rows))); + } + + /** @return list */ + public function cachedFinanceMembers(): array + { + return (array) Cache::remember( + self::FINANCE_MEMBERS_CACHE_KEY, + now()->addMinutes(max((int) config('dingtalk.finance_roster_cache_minutes', 720), 1)), + fn (): array => $this->financeMembers(), + ); + } + /** Minimal, bounded directory search for workflow selection; no HR dataset is cached. */ public function search(string $term): array { diff --git a/app/Utilities/SidebarMenu.php b/app/Utilities/SidebarMenu.php index a8ea341d..e6d9abf2 100644 --- a/app/Utilities/SidebarMenu.php +++ b/app/Utilities/SidebarMenu.php @@ -53,6 +53,9 @@ class SidebarMenu ['prototype-finance-reports', 'profit-report', '公司利润报表', 'request_quote'], ['prototype-finance-reports', 'asset-report', '公司资产报表', 'account_balance'], ]], + ['title' => '费比异常数据监控', 'items' => [ + ['fee-ratio-monitoring', 'overview', '异常数据监控', 'monitor_heart'], + ]], ]; $visiblePages = self::visiblePages($user); diff --git a/config/business_navigation.php b/config/business_navigation.php index 381fc6e2..d1f5eb7c 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -1037,6 +1037,24 @@ $navigation = [ ['slug' => 'payment-process-statistics', 'title' => '付款流程统计表'], ], ], + [ + 'slug' => 'fee-ratio-monitoring', + 'title' => '费比异常数据监控', + 'icon' => 'monitor_heart', + 'pages' => [ + [ + 'slug' => 'overview', + 'title' => '异常数据监控', + 'directory' => [ + 'icon' => 'monitor_heart', + 'status' => '待接入', + 'description' => '监控费用占收入比例异常的业务数据,集中展示平台、店铺、费用项目和异常结果。', + 'empty' => '费比异常数据尚未接入。提供取数来源、费用口径和异常阈值后,这里会显示可追溯的异常明细。', + 'fields' => [], + ], + ], + ], + ], [ 'slug' => 'other', 'title' => '其他', diff --git a/config/dingtalk.php b/config/dingtalk.php index 19b3b814..5a090830 100644 --- a/config/dingtalk.php +++ b/config/dingtalk.php @@ -12,6 +12,7 @@ return [ // Verified HR roots: 简尚财务中心 and 龙晨品牌中心/财务中心. 'finance_department_ids' => array_values(array_filter(array_map('trim', explode(',', env('DINGTALK_FINANCE_DEPARTMENT_IDS', '22848291,994080505'))))), + 'finance_roster_cache_minutes' => max((int) env('DINGTALK_FINANCE_ROSTER_CACHE_MINUTES', 720), 1), // Individually approved, current enterprise members; never names or whole departments. // This grants ordinary login only, with the exact courier page scope below. 'limited_login_user_ids' => array_values(array_filter(array_map('trim', explode(',', env('DINGTALK_LIMITED_LOGIN_USER_IDS', ''))))), @@ -46,6 +47,16 @@ return [ 'worklog' => [ 'enabled' => filter_var(env('DINGTALK_WORKLOG_ENABLED', true), FILTER_VALIDATE_BOOL), 'template_name' => env('DINGTALK_WORKLOG_TEMPLATE_NAME', '财务日报'), + 'template_names' => array_values(array_filter(array_map( + 'trim', + explode(',', (string) env('DINGTALK_WORKLOG_TEMPLATE_NAMES', '财务日报,空白日志')), + ))), + 'finance_only_templates' => array_values(array_filter(array_map( + 'trim', + explode(',', (string) env('DINGTALK_WORKLOG_FINANCE_ONLY_TEMPLATES', '空白日志')), + ))), + 'display_name' => env('DINGTALK_WORKLOG_DISPLAY_NAME', '财务日报 / 日志'), + 'penalty_start_date' => env('DINGTALK_WORKLOG_PENALTY_START_DATE', '2026-11-04'), 'userid' => env('DINGTALK_WORKLOG_USERID'), 'lookback_days' => (int) env('DINGTALK_WORKLOG_LOOKBACK_DAYS', 35), 'page_size' => min(max((int) env('DINGTALK_WORKLOG_PAGE_SIZE', 20), 1), 20), diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 54d4c195..b0211444 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -215,6 +215,10 @@ CRON_TZ=Asia/Shanghai # 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。 3,13,23,33,43,53 * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --source=snapshot --page-size=500 --max-pages=20 --quiet >/dev/null 2>&1 0 5 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-purchase-prices --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_Orders --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-online-daifa-price --quiet' >/dev/null 2>&1 +# 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖,补历史缺口,再刷新最近 7 天。 +10 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jst-order-labels:sync-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1 +# 业绩明细种菜金额:每天 09:30 核查标签覆盖,同步本月/上月种菜报销并重算种菜金额。 +30 9 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:planting-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1 # 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。 0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1 # 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index ebdcd1e9..3bfd3ded 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -219,6 +219,10 @@ CRON_TZ=Asia/Shanghai # 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。 3,13,23,33,43,53 * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --source=snapshot --page-size=500 --max-pages=20 --quiet >/dev/null 2>&1 0 5 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-purchase-prices --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_Orders --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-online-daifa-price --quiet' >/dev/null 2>&1 +# 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖,补历史缺口,再刷新最近 7 天。 +10 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jst-order-labels:sync-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1 +# 业绩明细种菜金额:每天 09:30 核查标签覆盖,同步本月/上月种菜报销并重算种菜金额。 +30 9 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:planting-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1 # 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。 0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1 # 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。 diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index 673bdba1..9a1873a9 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -21,8 +21,10 @@ "business-mirror:import-jd-wallet", "jst-order-labels:import-planting-rules", "jst-order-labels:import", + "jst-order-labels:sync-daily", "business:import-jushuitan-shop-balances", "pinduoduo-bills:import-authoritative", + "planting-details:sync-work-orders", "planting-details:import", "product-catalog:import-authoritative-export", "product:monthly-weighted-average:base", diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 0a90b63f..fba6ce81 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -8,8 +8,8 @@ is_import=0 CAIWU_BATCH_CALLER_DIR="$PWD" export CAIWU_BATCH_CALLER_DIR case "${1:-}" in - *:import|*:import-*|*:import:*|product:monthly-weighted-average:base) is_import=1 ;; - jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; + *:import|*:import-*|*:import:*|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;; + jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; *) echo 'Unsupported finance batch command' >&2; exit 64 ;; esac case "${1:-}" in diff --git a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php index 0ce15d89..58ba3b18 100644 --- a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php @@ -96,6 +96,7 @@ class AlipayBills extends Controller 'expense' => 0, 'opening_balance' => 0, 'opening_balance_date' => null, + 'opening_balance_source' => null, 'balance' => 0, 'count' => 0, ], diff --git a/modules/EcommerceFinance/Repositories/DingWorklogMirrorRepository.php b/modules/EcommerceFinance/Repositories/DingWorklogMirrorRepository.php index e1ae49a2..fdbdd7cc 100644 --- a/modules/EcommerceFinance/Repositories/DingWorklogMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/DingWorklogMirrorRepository.php @@ -117,7 +117,10 @@ class DingWorklogMirrorRepository $state = $this->state(); $values = [ 'source_key' => 'dingtalk_worklog', - 'source_object' => (string) config('dingtalk.worklog.template_name', '财务日报'), + 'source_object' => implode(' / ', (array) config( + 'dingtalk.worklog.template_names', + [config('dingtalk.worklog.template_name', '财务日报')], + )), 'target_table' => self::TABLE, 'status' => 'failed', 'run_mode' => 'incremental', @@ -186,6 +189,31 @@ class DingWorklogMirrorRepository ->all(); } + public function earliestStatisticsDate(): ?string + { + $date = $this->connection->table(self::TABLE)->min('statistics_date'); + + return $date ? (string) $date : null; + } + + /** + * @return list + */ + public function submittedDatesByUser(string $from, string $to): array + { + return $this->connection->table(self::TABLE) + ->whereBetween('statistics_date', [$from, $to]) + ->orderBy('statistics_date') + ->get(['creator_userid', 'creator_name', 'statistics_date']) + ->map(static fn (object $row): array => [ + 'creator_userid' => (string) ($row->creator_userid ?? ''), + 'creator_name' => (string) ($row->creator_name ?? ''), + 'statistics_date' => (string) $row->statistics_date, + ]) + ->values() + ->all(); + } + public static function statisticsDate(CarbonInterface|int|string $submittedAt): Carbon { $submitted = self::submittedAt($submittedAt)->timezone( diff --git a/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php index 9f9664c1..356d2f76 100644 --- a/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php +++ b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php @@ -84,6 +84,7 @@ class TaobaoAlipaySettlementBillRepository 'expense' => $expense, 'opening_balance' => $opening['balance'], 'opening_balance_date' => $opening['date'], + 'opening_balance_source' => $opening['source'], 'balance' => round($opening['balance'] + $income - $expense, 2), 'count' => $total, ], @@ -178,18 +179,20 @@ class TaobaoAlipaySettlementBillRepository * * 同一秒可能有多笔流水,按源表行号继续取最后一笔,避免同一时间点重复计入。 * - * @return array{balance:float,date:?string} + * @return array{balance:float,date:?string,source:string} */ private function openingBalance(array $filters): array { $start = $this->date($filters['start'] ?? null) ?? $this->date($filters['end'] ?? null); if ($start === null) { - return ['balance' => 0.0, 'date' => null]; + return ['balance' => 0.0, 'date' => null, 'source' => 'none']; } $monthStart = $start->modify('first day of this month'); + $nextMonthStart = $monthStart->modify('+1 month'); $cutoff = $monthStart->format('Y-m-d') . ' 00:00:00'; + $periodEnd = $nextMonthStart->format('Y-m-d') . ' 00:00:00'; $store = trim((string) ($filters['store_name'] ?? '')); $importVersion = (string) ($this->connection->table(self::IMPORT_TABLE) ->where('status', 'succeeded') @@ -200,16 +203,23 @@ class TaobaoAlipaySettlementBillRepository $importVersion, ])); - $balance = Cache::remember( + $opening = Cache::remember( $cacheKey, self::OPENING_BALANCE_CACHE_SECONDS, - function () use ($cutoff, $store): float { + function () use ($cutoff, $periodEnd, $store): array { $ranked = $this->connection->table(self::ROW_TABLE) ->where('occurred_at', '<', $cutoff) ->whereNotNull('alipay_account') ->where('alipay_account', '<>', '') ->when($store !== '', fn (Builder $query) => $query->where('store_name', $store)) - ->select(['alipay_account', 'occurred_at', 'source_row_number', 'balance_amount']) + ->select([ + 'alipay_account', + 'occurred_at', + 'source_row_number', + 'income_amount', + 'expense_amount', + 'balance_amount', + ]) ->selectRaw( 'ROW_NUMBER() OVER (' . 'PARTITION BY alipay_account ' . @@ -217,16 +227,60 @@ class TaobaoAlipaySettlementBillRepository ') AS row_rank', ); - return round((float) $this->connection->query() + $latestRows = $this->connection->query() ->fromSub($ranked, 'latest_balances') ->where('row_rank', 1) - ->sum('balance_amount'), 2); + ->get(); + + if ($latestRows->isNotEmpty()) { + return [ + 'balance' => round((float) $latestRows->sum('balance_amount'), 2), + 'source' => 'previous_period', + ]; + } + + // 首个导入月份没有上月快照时,用当月首笔余额倒推期初: + // 期初 = 首笔余额 - 首笔收入 + 首笔支出。 + $firstRows = $this->connection->table(self::ROW_TABLE) + ->where('occurred_at', '>=', $cutoff) + ->where('occurred_at', '<', $periodEnd) + ->whereNotNull('alipay_account') + ->where('alipay_account', '<>', '') + ->when($store !== '', fn (Builder $query) => $query->where('store_name', $store)) + ->select([ + 'alipay_account', + 'occurred_at', + 'source_row_number', + 'income_amount', + 'expense_amount', + 'balance_amount', + ]) + ->selectRaw( + 'ROW_NUMBER() OVER (' . + 'PARTITION BY alipay_account ' . + 'ORDER BY occurred_at ASC, source_row_number ASC' . + ') AS row_rank', + ); + $first = $this->connection->query() + ->fromSub($firstRows, 'first_balances') + ->where('row_rank', 1) + ->get(); + + return [ + 'balance' => round((float) $first->sum( + static fn (object $row): float => (float) $row->balance_amount + - (float) $row->income_amount + + (float) $row->expense_amount, + ), 2), + 'source' => 'first_row_estimate', + ]; }, ); return [ - 'balance' => (float) $balance, + 'balance' => (float) $opening['balance'], 'date' => $monthStart->modify('-1 day')->format('Y-m-d'), + 'source' => (string) $opening['source'], ]; } diff --git a/modules/EcommerceFinance/Services/DingWorklogPenaltyCalculator.php b/modules/EcommerceFinance/Services/DingWorklogPenaltyCalculator.php new file mode 100644 index 00000000..d0360de3 --- /dev/null +++ b/modules/EcommerceFinance/Services/DingWorklogPenaltyCalculator.php @@ -0,0 +1,145 @@ +, + * missed_count:int, + * penalty_points:string, + * penalty_points_formatted:string, + * penalty_formula:string + * }> + * } + */ + public function summary(string $from, string $to, CarbonInterface $at): array + { + $timezone = (string) config('app.timezone', 'Asia/Shanghai'); + $now = Carbon::instance($at)->timezone($timezone); + $requestedStart = Carbon::parse($from, $timezone)->startOfDay(); + $requestedEnd = Carbon::parse($to, $timezone)->startOfDay(); + $configuredStart = Carbon::parse( + (string) config('dingtalk.worklog.penalty_start_date', '2026-11-04'), + $timezone, + )->startOfDay(); + $latestClosed = $now->hour < 12 + ? $now->subDays(2)->startOfDay() + : $now->subDay()->startOfDay(); + $end = $requestedEnd->lessThan($latestClosed) ? $requestedEnd->copy() : $latestClosed; + + $earliest = $this->repository->earliestStatisticsDate(); + if ($earliest === null) { + return [ + 'start_date' => null, + 'end_date' => null, + 'total_points' => '0', + 'total_points_formatted' => '0', + 'members' => [], + ]; + } + $earliestDate = Carbon::parse($earliest, $timezone)->startOfDay(); + $start = $requestedStart->greaterThan($earliestDate) ? $requestedStart->copy() : $earliestDate; + if ($configuredStart->greaterThan($start)) { + $start = $configuredStart; + } + if ($start->greaterThan($end)) { + return [ + 'start_date' => null, + 'end_date' => null, + 'total_points' => '0', + 'total_points_formatted' => '0', + 'members' => [], + ]; + } + + $submitted = []; + foreach ($this->repository->submittedDatesByUser($start->toDateString(), $end->toDateString()) as $row) { + if ($row['creator_userid'] !== '') { + $submitted[$row['creator_userid']][$row['statistics_date']] = true; + } + } + + $members = []; + foreach ($this->roster->cachedFinanceMembers() as $member) { + $userId = trim((string) ($member['userid'] ?? '')); + if ($userId === '') { + continue; + } + $members[$userId] = [ + 'userid' => $userId, + 'name' => trim((string) ($member['name'] ?? '')) ?: $userId, + 'missed_dates' => [], + 'missed_count' => 0, + 'penalty_points' => '0', + 'penalty_formula' => [], + ]; + } + + foreach ($members as $userId => &$member) { + $sequence = 0; + for ($date = $start->copy(); $date->lessThanOrEqualTo($end); $date->addDay()) { + $dateKey = $date->toDateString(); + if (isset($submitted[$userId][$dateKey])) { + continue; + } + + $sequence++; + $increment = bcmul(self::BASE_POINTS, bcpow('2', (string) ($sequence - 1), 0), 0); + $member['penalty_points'] = bcadd($member['penalty_points'], $increment, 0); + $member['penalty_formula'][] = $increment; + $member['missed_dates'][] = $dateKey; + $member['missed_count']++; + } + } + unset($member); + + $rows = array_values(array_filter($members, static fn (array $member): bool => $member['missed_count'] > 0)); + usort($rows, static fn (array $left, array $right): int => + (bccomp($right['penalty_points'], $left['penalty_points']) ?: strcmp($left['name'], $right['name'])) + ); + $totalPoints = array_reduce( + $rows, + static fn (string $total, array $member): string => bcadd($total, $member['penalty_points'], 0), + '0', + ); + + return [ + 'start_date' => $start->toDateString(), + 'end_date' => $end->toDateString(), + 'total_points' => $totalPoints, + 'total_points_formatted' => $this->formatPoints($totalPoints), + 'members' => array_map(function (array $member): array { + $member['penalty_points_formatted'] = $this->formatPoints($member['penalty_points']); + $member['penalty_formula'] = implode(' + ', $member['penalty_formula']); + + return $member; + }, $rows), + ]; + } + + private function formatPoints(string $points): string + { + return preg_replace('/\B(?=(\d{3})+(?!\d))/', ',', $points) ?: $points; + } +} diff --git a/modules/EcommerceFinance/View/DingWorklogStatisticsPageData.php b/modules/EcommerceFinance/View/DingWorklogStatisticsPageData.php index 2e481d4a..2747acdd 100644 --- a/modules/EcommerceFinance/View/DingWorklogStatisticsPageData.php +++ b/modules/EcommerceFinance/View/DingWorklogStatisticsPageData.php @@ -5,12 +5,14 @@ namespace Modules\EcommerceFinance\View; use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Modules\EcommerceFinance\Repositories\DingWorklogMirrorRepository; +use Modules\EcommerceFinance\Services\DingWorklogPenaltyCalculator; use Throwable; class DingWorklogStatisticsPageData { public function __construct( private readonly DingWorklogMirrorRepository $repository, + private readonly DingWorklogPenaltyCalculator $penaltyCalculator, ) {} public function page(Request $request): array @@ -42,24 +44,46 @@ class DingWorklogStatisticsPageData $daily = []; $selectedDate = $this->date($request->query('date'))?->toDateString(); + $showDetails = $request->boolean('details'); $submissions = []; + $penalty = [ + 'start_date' => null, + 'end_date' => null, + 'total_points' => '0', + 'total_points_formatted' => '0', + 'members' => [], + ]; + $penaltyError = null; if ($this->repository->available()) { try { $daily = $this->repository->dailySummary($from->toDateString(), $to->toDateString()); $selectedDate ??= $daily[0]['statistics_date'] ?? $latestStatisticsDate->toDateString(); - $submissions = array_map(static fn (object $row): array => [ - 'report_id' => (string) $row->report_id, - 'template_name' => (string) ($row->template_name ?? ''), - 'creator_userid' => (string) ($row->creator_userid ?? ''), - 'creator_name' => (string) ($row->creator_name ?? ''), - 'submitted_at' => (string) $row->submitted_at, - 'statistics_date' => (string) $row->statistics_date, - ], $this->repository->submissionsForDate($selectedDate)); + if ($showDetails) { + $submissions = array_map(static fn (object $row): array => [ + 'report_id' => (string) $row->report_id, + 'template_name' => (string) ($row->template_name ?? ''), + 'creator_userid' => (string) ($row->creator_userid ?? ''), + 'creator_name' => (string) ($row->creator_name ?? ''), + 'submitted_at' => (string) $row->submitted_at, + 'statistics_date' => (string) $row->statistics_date, + ], $this->repository->submissionsForDate($selectedDate)); + } } catch (Throwable $exception) { report($exception); $syncState = 'failed'; $errorCode = 'dingtalk_worklog_read_failed'; } + + try { + $penalty = $this->penaltyCalculator->summary( + $from->toDateString(), + $to->toDateString(), + now(), + ); + } catch (Throwable $exception) { + report($exception); + $penaltyError = '日志漏写扣分暂时无法计算。'; + } } $currentDate = $latestStatisticsDate->toDateString(); @@ -91,9 +115,12 @@ class DingWorklogStatisticsPageData 'worklogCurrent' => $current, 'worklogDaily' => $daily, 'worklogSubmissions' => $submissions, + 'worklogShowDetails' => $showDetails, + 'worklogPenalty' => $penalty, + 'worklogPenaltyError' => $penaltyError, 'worklogDays' => (int) $from->diffInDays($to) + 1, 'worklogTotalSubmissions' => array_sum(array_column($daily, 'submission_count')), - 'worklogTemplateName' => (string) config('dingtalk.worklog.template_name', '财务日报'), + 'worklogTemplateName' => (string) config('dingtalk.worklog.display_name', '财务日报 / 日志'), 'worklogCutoffAt' => $latestStatisticsDate->copy()->addDay()->setTime(12, 0)->toDateTimeString(), ]; } diff --git a/resources/assets/js/components/business/TaobaoAlipayBills.vue b/resources/assets/js/components/business/TaobaoAlipayBills.vue index 6b652310..5f305bcc 100644 --- a/resources/assets/js/components/business/TaobaoAlipayBills.vue +++ b/resources/assets/js/components/business/TaobaoAlipayBills.vue @@ -163,13 +163,13 @@ const SORTABLE = ['occurred_at', 'income', 'expense', 'balance', 'record_code']; export default { name: 'TaobaoAlipayBills', components: { TableColumnSettings, flatPicker, [Select.name]: Select, [Option.name]: Option }, props: { apiBase: { type: String, required: true }, exportBase: { type: String, required: true }, progressBase: { type: String, default: '' }, userKey: { type: [String, Number], required: true } }, - data() { return { loading: false, error: '', rows: [], configuredColumns: [], summary: { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, balance: 0, count: 0 }, total: 0, currentPage: 1, lastPage: 1, perPage: 20, filters: { store_name: '', ledger_remark: '', source_channel: '', bill_item: '', business_type: '', ...currentMonthRange(), keyword: '' }, filterOptions: { shops: [], bill_items: [], ledger_remarks: [] }, filterOptionsLoading: false, filterOptionsError: false, sort: { key: 'occurred_at', dir: 'desc' }, exportMode: 'filtered-visible', exporting: false, exportModalOpen: false, exportTasks: [], exportHint: '导出在后台生成,成功后点「下载」;期间可以继续查看其它页面。', exportTimer: null }; }, + data() { return { loading: false, error: '', rows: [], configuredColumns: [], summary: { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, opening_balance_source: null, balance: 0, count: 0 }, total: 0, currentPage: 1, lastPage: 1, perPage: 20, filters: { store_name: '', ledger_remark: '', source_channel: '', bill_item: '', business_type: '', ...currentMonthRange(), keyword: '' }, filterOptions: { shops: [], bill_items: [], ledger_remarks: [] }, filterOptionsLoading: false, filterOptionsError: false, sort: { key: 'occurred_at', dir: 'desc' }, exportMode: 'filtered-visible', exporting: false, exportModalOpen: false, exportTasks: [], exportHint: '导出在后台生成,成功后点「下载」;期间可以继续查看其它页面。', exportTimer: null }; }, computed: { defaultColumns() { return COLUMNS; }, visibleColumns() { return this.configuredColumns.filter((column) => column.visible); }, visibleGroups() { return this.visibleColumns.reduce((groups, column) => { const last = groups[groups.length - 1]; if (last && last.label === column.group) last.span += 1; else groups.push({ label: column.group, span: 1 }); return groups; }, []); }, stats() { return [ - { label: '期初余额', value: this.moneyWan(this.summary.opening_balance), note: this.summary.opening_balance_date ? `截至 ${this.summary.opening_balance_date} 最后一笔` : '上月最后一笔', className: '' }, + { label: '期初余额', value: this.moneyWan(this.summary.opening_balance), note: this.summary.opening_balance_source === 'first_row_estimate' ? '首月按首笔余额倒推' : (this.summary.opening_balance_date ? `截至 ${this.summary.opening_balance_date} 最后一笔` : '上月最后一笔'), className: '' }, { label: '收入合计', value: this.moneyWan(this.summary.income), note: `${this.summary.count} 笔交易`, className: 'is-income' }, { label: '支出合计', value: this.moneyWan(this.summary.expense), note: '按当前筛选', className: 'is-expense' }, { label: '余额', value: this.moneyWan(this.summary.balance), note: '期初余额 + 收入合计 - 支出合计', className: '' }, @@ -187,7 +187,7 @@ export default { mounted() { this.fetchFilterOptions(); this.fetch(); }, methods: { async fetchFilterOptions() { this.filterOptionsLoading = true; this.filterOptionsError = false; try { const response = await window.axios.get(`${this.apiBase}/filter-options`); const body = response.data || {}; this.filterOptions = { shops: Array.isArray(body.shops) ? body.shops : [], bill_items: Array.isArray(body.bill_items) ? body.bill_items : [], ledger_remarks: Array.isArray(body.ledger_remarks) ? body.ledger_remarks : [] }; } catch (error) { this.filterOptionsError = true; } finally { this.filterOptionsLoading = false; } }, - async fetch() { this.loading = true; this.error = ''; try { const response = await window.axios.get(this.apiBase, { params: { ...this.filters, sort: this.sort.key, dir: this.sort.dir, limit: this.perPage, page: this.currentPage } }); const body = response.data || {}; this.rows = body.data || []; this.total = body.total || 0; this.currentPage = body.current_page || 1; this.lastPage = body.last_page || 1; this.perPage = body.per_page || this.perPage; this.summary = body.summary || { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, balance: 0, count: 0 }; } catch (error) { this.rows = []; this.total = 0; this.summary = { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, balance: 0, count: 0 }; this.error = (error.response && error.response.data && error.response.data.message) || '淘系支付宝账单暂时无法读取,请稍后重试。'; } finally { this.loading = false; } }, + async fetch() { this.loading = true; this.error = ''; try { const response = await window.axios.get(this.apiBase, { params: { ...this.filters, sort: this.sort.key, dir: this.sort.dir, limit: this.perPage, page: this.currentPage } }); const body = response.data || {}; this.rows = body.data || []; this.total = body.total || 0; this.currentPage = body.current_page || 1; this.lastPage = body.last_page || 1; this.perPage = body.per_page || this.perPage; this.summary = body.summary || { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, opening_balance_source: null, balance: 0, count: 0 }; } catch (error) { this.rows = []; this.total = 0; this.summary = { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, opening_balance_source: null, balance: 0, count: 0 }; this.error = (error.response && error.response.data && error.response.data.message) || '淘系支付宝账单暂时无法读取,请稍后重试。'; } finally { this.loading = false; } }, applyFilters() { if (this.invalidDateRange) return; this.currentPage = 1; this.fetch(); }, resetFilters() { this.filters = { store_name: '', ledger_remark: '', source_channel: '', bill_item: '', business_type: '', ...currentMonthRange(), keyword: '' }; this.applyFilters(); }, openDatePicker(refName) { const picker = this.$refs[refName]; if (picker && picker.fp) picker.fp.open(); }, // 选日期不自动查询:日期是一对(开始/结束),中途触发会先按半截条件查全表,很慢。改完点「查询」再生效。 diff --git a/resources/views/business/pages/other/log-statistics.blade.php b/resources/views/business/pages/other/log-statistics.blade.php index 172220cc..0938a727 100644 --- a/resources/views/business/pages/other/log-statistics.blade.php +++ b/resources/views/business/pages/other/log-statistics.blade.php @@ -37,6 +37,38 @@ line-height: 1.65; } + .log-statistics-penalty-rule { + display: flex; + align-items: flex-start; + gap: 0.75rem; + padding: 0.9rem 1rem; + border: 1px solid var(--vip-content-accent, #B9954F); + border-left-width: 4px; + border-radius: 8px; + background: var(--vip-content-accent-soft, #F7F0DE); + } + + .log-statistics-penalty-rule .material-icons-outlined { + flex: 0 0 auto; + color: var(--vip-content-accent-dark, #856632); + font-size: 1.2rem; + } + + .log-statistics-penalty-rule strong { + display: block; + margin-bottom: 0.15rem; + color: var(--vip-content-ink, #171717); + font-size: 0.78rem; + font-weight: 600; + } + + .log-statistics-penalty-rule span { + display: block; + color: var(--vip-content-muted, #595959); + font-size: 0.75rem; + line-height: 1.7; + } + .log-statistics-alert { display: flex; align-items: flex-start; @@ -121,6 +153,19 @@ background: var(--vip-surface, #fff); } + .log-statistics-card.is-link { + color: inherit; + text-decoration: none; + transition: border-color 150ms ease, background 150ms ease; + } + + .log-statistics-card.is-link:hover, + .log-statistics-card.is-link:focus-visible { + border-color: var(--vip-content-accent, #B9954F); + background: var(--vip-content-accent-soft, #F7F0DE); + outline: none; + } + .log-statistics-card span { color: var(--vip-content-muted, #595959); font-size: 0.6875rem; @@ -132,6 +177,17 @@ font-variant-numeric: tabular-nums; } + .log-statistics-card a { + color: inherit; + text-decoration: none; + } + + .log-statistics-card__hint { + color: var(--vip-content-accent-dark, #856632) !important; + font-size: 0.625rem !important; + font-weight: 600; + } + .log-statistics-panel { overflow: hidden; border: 1px solid var(--vip-border, #D8D2C7); @@ -159,6 +215,27 @@ font-size: 0.6875rem; } + .log-statistics-detail-actions { + display: inline-flex; + align-items: center; + gap: 0.75rem; + } + + .log-statistics-collapse { + display: inline-flex; + min-height: 1.75rem; + align-items: center; + gap: 0.25rem; + padding: 0 0.55rem; + border: 1px solid var(--vip-border, #D8D2C7); + border-radius: 5px; + background: var(--vip-surface, #fff); + color: var(--vip-content-accent-dark, #856632); + font-size: 0.6875rem; + font-weight: 600; + text-decoration: none; + } + .log-statistics-table-wrap { overflow: auto; max-height: 28rem; @@ -203,6 +280,12 @@ background: var(--vip-content-accent-soft, #F7F0DE); } + .log-statistics-table .is-wrapped { + min-width: 18rem; + white-space: normal; + line-height: 1.6; + } + .log-statistics-empty { padding: 2rem 1rem; color: var(--vip-content-muted, #595959); @@ -231,6 +314,14 @@ +
+ +
+ 日志漏写扣分规则 + 第 1 次漏写扣 10 分,第 2 次扣 20 分,第 3 次扣 40 分,之后每次在上一次基础上翻倍并累计。只统计已经超过“次日 12:00”截止时间的日期。 +
+
+ @if ($worklogState['permission_required']) diff --git a/resources/views/business/pages/partials/final-dataset-table.blade.php b/resources/views/business/pages/partials/final-dataset-table.blade.php index 251736b7..3f782fbe 100644 --- a/resources/views/business/pages/partials/final-dataset-table.blade.php +++ b/resources/views/business/pages/partials/final-dataset-table.blade.php @@ -9,6 +9,8 @@ $finalKeyword = $payablesFinal['keyword'] ?? ''; $finalActions = $payablesFinal['actions'] ?? ''; $finalMaintenance = ['dataset' => $finalDataset, 'fields' => $finalFields]; + $freezeThroughSupplier = $finalDataset === 'supplier-payables-report'; + $freezeThroughSupplierFields = ['summary_month', 'checker', 'settlement_method', 'company', 'supplier']; @endphp
@@ -42,6 +44,15 @@ .payables-final-table .is-number { text-align: right; } .payables-final-table .is-empty td { height: 8rem; color: var(--vip-content-muted, #595959); text-align: center; } .payables-final-pagination { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 0.75rem 1rem; color: var(--vip-content-muted, #595959); font-size: 0.8125rem; } + .payables-final-table--freeze-through-supplier { border-collapse: separate; border-spacing: 0; } + .payables-final-table--freeze-through-supplier th, + .payables-final-table--freeze-through-supplier td { border-right: 1px solid var(--vip-border, #D8D2C7); } + .payables-final-table--freeze-through-supplier th:last-child, + .payables-final-table--freeze-through-supplier td:last-child { border-right: 0; } + .payables-final-table--freeze-through-supplier tbody tr:hover td { background: #FBF8F0; } + .payables-final-freeze-column { position: sticky; z-index: 1; background: var(--vip-surface, #FFFFFF); } + .payables-final-table thead .payables-final-freeze-column { z-index: 3; background: var(--vip-content-accent-soft, #F7F0DE); } + .payables-final-freeze-edge { box-shadow: inset -2px 0 0 var(--vip-content-accent, #B9954F); }
@@ -77,12 +88,26 @@
- +
$freezeThroughSupplier, + ])> - + @foreach ($finalFields as $field) - + @php $freezeField = $freezeThroughSupplier && in_array($field['name'], $freezeThroughSupplierFields, true); @endphp + @endforeach @@ -90,10 +115,21 @@ @forelse ($finalRows ?? [] as $index => $row) - + @foreach ($finalFields as $field) @php $value = $row[$field['name']] ?? null; @endphp -
序号 $freezeThroughSupplier]) + >序号 $field['type'] === 'number'])>{{ $field['label'] }} $field['type'] === 'number', + 'payables-final-freeze-column' => $freezeField, + 'payables-final-freeze-edge' => $freezeThroughSupplier && $field['name'] === 'supplier', + ]) + >{{ $field['label'] }}
{{ ($finalRows->firstItem() ?? 1) + $index }} $freezeThroughSupplier]) + >{{ ($finalRows->firstItem() ?? 1) + $index }} $field['type'] === 'number'])> + @php $freezeField = $freezeThroughSupplier && in_array($field['name'], $freezeThroughSupplierFields, true); @endphp + $field['type'] === 'number', + 'payables-final-freeze-column' => $freezeField, + 'payables-final-freeze-edge' => $freezeThroughSupplier && $field['name'] === 'supplier', + ]) + > @if ($value === null || $value === '') - @elseif ($field['type'] === 'number' && is_numeric($value)) @@ -119,7 +155,7 @@ 上一页 @endif 第 {{ $finalRows?->currentPage() ?? 1 }} 页 / 共 {{ $finalRows?->lastPage() ?? 1 }} 页 - · 每页 {{ $finalRows?->perPage() ?? (in_array($finalDataset, ['payment-reconciliation', 'return-reconciliation'], true) ? 15 : 50) }} 条 + · 每页 {{ $finalRows?->perPage() ?? (in_array($finalDataset, ['payment-reconciliation', 'return-reconciliation', 'supplier-payables-report'], true) ? 15 : 50) }} 条 @if ($finalRows?->hasMorePages()) 下一页 @endif @@ -128,6 +164,51 @@ +@if ($freezeThroughSupplier) + +@endif + @include('business.pages.supplier-payables.maintenance-blade-modal', [ 'content' => ['supplierPayableMaintenance' => $finalMaintenance], 'supplierMaintenanceAction' => $finalActions, diff --git a/scripts/erp-daily-bills/README.md b/scripts/erp-daily-bills/README.md index d96b99b3..7a328877 100644 --- a/scripts/erp-daily-bills/README.md +++ b/scripts/erp-daily-bills/README.md @@ -45,6 +45,24 @@ docker exec -u www-data caiwu_app php artisan business-mirror:verify-erp-daily-c 命令会逐个月份检查期间起止范围、有效版本行数和登记行数;缺月、只导到月中或行数不一致都会返回失败。 +## 聚水潭订单标签明细 + +聚水潭订单标签明细复用已同步的 `ops_jst_orders`,不经过浏览器导出。生产宿主机每天 06:10 在订单镜像 05:00 同步后执行: + +```bash +sh /opt/caiwuxitong/run-finance-batch.sh jst-order-labels:sync-daily --from=2026-10-01 --company=1 +``` + +任务会先逐日比较源订单与标签明细的订单覆盖。历史缺口按连续日期补导;历史检查未通过时不继续拉取新数据。通过后替换刷新最近 7 天,并再次复核整段覆盖。手动预览可加 `--dry-run --json`。 + +业绩明细的种菜金额每天 09:30 单独刷新: + +```bash +sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:planting-daily --from=2026-10-01 --company=1 +``` + +任务先确认标签明细覆盖完整,再同步当前月和上月的种菜报销工单,最后对这两个月执行 `store-receipt:order-match:sync --planting-only`。种菜订单号取“种菜报销明细订单号”和“聚水潭是否种菜订单=是”的并集,命中订单的种菜金额取该业绩行收入金额。 + ## 组成 | 文件 | 作用 | diff --git a/tests/Feature/Business/PagesTest.php b/tests/Feature/Business/PagesTest.php index 9da3a360..9138f464 100644 --- a/tests/Feature/Business/PagesTest.php +++ b/tests/Feature/Business/PagesTest.php @@ -21,6 +21,7 @@ use Modules\EcommerceFinance\Repositories\NonJingxiRefundMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository; use Modules\EcommerceFinance\Repositories\ThirdPartyWarehouseStorageMirrorRepository; +use Modules\EcommerceFinance\Services\DingWorklogPenaltyCalculator; use Modules\EcommerceFinance\Services\RefundPendingSyncStatus; use Modules\EcommerceFinance\View\OrderDataPageData; use Tests\Feature\FeatureTestCase; @@ -130,6 +131,90 @@ class PagesTest extends FeatureTestCase ->once() ->andReturn('https://open-dev.dingtalk.com/appscope/apply?content=test'); $this->app->instance(DingWorklogMirrorRepository::class, $repository); + $penalty = Mockery::mock(DingWorklogPenaltyCalculator::class); + $penalty->shouldReceive('summary')->once()->andReturn([ + 'start_date' => '2026-11-04', + 'end_date' => '2026-11-04', + 'total_points' => '70', + 'total_points_formatted' => '70', + 'members' => [[ + 'userid' => 'jiangling', + 'name' => '江陵', + 'missed_dates' => ['2026-10-22', '2026-10-24', '2026-10-30'], + 'missed_count' => 3, + 'penalty_points' => '70', + 'penalty_points_formatted' => '70', + 'penalty_formula' => '10 + 20 + 40', + ]], + ]); + $this->app->instance(DingWorklogPenaltyCalculator::class, $penalty); + + try { + $this->loginAs() + ->get(route('business.pages.show', [ + 'section' => 'other', + 'page' => 'log-statistics', + 'date' => '2026-11-03', + 'details' => 1, + ])) + ->assertOk() + ->assertSee('data-log-statistics', false) + ->assertSeeText('钉钉 财务日报 / 日志 · 次日 12:00 截止') + ->assertSeeText('次日 12:00 前补交的日志,统一计入统计日') + ->assertSee('data-worklog-penalty-rule', false) + ->assertSeeText('日志漏写扣分规则') + ->assertSeeText('qyapi_report_query') + ->assertSeeText('前往钉钉开通') + ->assertSeeText('2026-11-03') + ->assertSeeText('秋香') + ->assertSeeText('李斯') + ->assertSeeText('2026-11-04 10:26:00') + ->assertSee('id="worklog-detail"', false) + ->assertSee('title="查看 2026-11-03 提交人姓名"', false) + ->assertSee('title="查看 2026-11-03 日志明细"', false) + ->assertSee('收起明细') + ->assertSeeText('点击查看扣分明细') + ->assertSeeText('点击查看提交人') + ->assertSeeText('点击查看日志明细') + ->assertDontSeeText('点击查看每日统计') + ->assertSee('data-worklog-penalty', false) + ->assertSeeText('2026-11-04 起扣分合计') + ->assertSeeText('第 1 次漏写扣 10 分') + ->assertSeeText('江陵') + ->assertSeeText('10 + 20 + 40') + ->assertSeeText('70'); + } finally { + Carbon::setTestNow(); + } + } + + public function testLogStatisticsPageHidesTheEmptyPenaltyPanel(): void + { + Carbon::setTestNow(Carbon::parse('2026-11-05 15:00:00', 'Asia/Shanghai')); + + $repository = Mockery::mock(DingWorklogMirrorRepository::class); + $repository->shouldReceive('available')->andReturnTrue(); + $repository->shouldReceive('state')->once()->andReturn([ + 'status' => 'succeeded', + 'last_error_code' => null, + 'last_attempted_at' => '2026-11-05 14:00:00', + 'last_succeeded_at' => '2026-11-05 14:00:00', + 'mirror_row_count' => 1, + ]); + $repository->shouldReceive('dailySummary')->once()->andReturn([]); + $repository->shouldNotReceive('submissionsForDate'); + $repository->shouldNotReceive('permissionApplyUrl'); + $this->app->instance(DingWorklogMirrorRepository::class, $repository); + + $penalty = Mockery::mock(DingWorklogPenaltyCalculator::class); + $penalty->shouldReceive('summary')->once()->andReturn([ + 'start_date' => '2026-11-04', + 'end_date' => '2026-11-04', + 'total_points' => '0', + 'total_points_formatted' => '0', + 'members' => [], + ]); + $this->app->instance(DingWorklogPenaltyCalculator::class, $penalty); try { $this->loginAs() @@ -138,15 +223,11 @@ class PagesTest extends FeatureTestCase 'page' => 'log-statistics', ])) ->assertOk() - ->assertSee('data-log-statistics', false) - ->assertSeeText('钉钉 财务日报 · 次日 12:00 截止') - ->assertSeeText('次日 12:00 前补交的日志,统一计入统计日') - ->assertSeeText('qyapi_report_query') - ->assertSeeText('前往钉钉开通') - ->assertSeeText('2026-11-03') - ->assertSeeText('秋香') - ->assertSeeText('李斯') - ->assertSeeText('2026-11-04 10:26:00'); + ->assertSeeText('2026-11-04 起扣分合计') + ->assertDontSeeText('点击查看扣分明细') + ->assertDontSeeText('日志漏写扣分统计') + ->assertDontSeeText('当前时间范围暂无漏写扣分记录。') + ->assertDontSee('id="worklog-penalty"', false); } finally { Carbon::setTestNow(); } diff --git a/tests/Feature/Business/SupplierPayableFinalPagesTest.php b/tests/Feature/Business/SupplierPayableFinalPagesTest.php index 954453f1..5ed99193 100644 --- a/tests/Feature/Business/SupplierPayableFinalPagesTest.php +++ b/tests/Feature/Business/SupplierPayableFinalPagesTest.php @@ -295,6 +295,53 @@ class SupplierPayableFinalPagesTest extends FeatureTestCase ->assertDontSeeText('PM-01'); } + public function test_final_supplier_payables_report_paginates_and_freezes_through_supplier(): void + { + $records = []; + for ($index = 1; $index <= 20; $index++) { + $records[sprintf('supplier-payable:%02d', $index)] = [ + 'summary_month' => '2026-09', + 'checker' => sprintf('对账人%02d', $index), + 'settlement_method' => '月结', + 'company' => sprintf('供应商主体%02d', $index), + 'supplier' => sprintf('SUP-%02d', $index), + 'express_freight' => '0', + ]; + } + app(SupplierPayableOverrideStore::class)->saveBatch( + 'final:supplier:supplier-payables-report', + $records, + (int) $this->company->id, + (int) $this->user->id, + ); + + $baseUrl = route('business.pages.show', [ + 'company_id' => (int) $this->company->id, + 'section' => 'supplier-payables-final', + 'page' => 'supplier-payables-report', + ]); + $url = fn (int $page): string => $baseUrl . '?page=' . $page; + + $this->loginAs()->get($url(1)) + ->assertOk() + ->assertSee('payables-final-table--freeze-through-supplier', false) + ->assertSee('data-final-column="summary_month"', false) + ->assertSee('data-final-column="supplier"', false) + ->assertSee('payables-final-freeze-edge', false) + ->assertSee('data-caiwu-replay', false) + ->assertSeeText('每页 15 条') + ->assertSeeText('第 1 页 / 共 2 页') + ->assertSeeText('SUP-01') + ->assertDontSeeText('SUP-16'); + + $this->loginAs()->get($url(2)) + ->assertOk() + ->assertSeeText('第 2 页 / 共 2 页') + ->assertSeeText('SUP-16') + ->assertSeeText('SUP-20') + ->assertDontSeeText('SUP-01'); + } + public function test_final_import_reads_files_larger_than_one_chunk(): void { $lines = ['月份,入库单号,采购单号,日期,供应商,货号,商品编码,规格名称,数量,单价,金额,预估单价,预估金额,供应商商品编码,备注,仓库名称,快递名称,快递单号,未发出,对账人']; diff --git a/tests/Feature/Console/SyncDingWorklogsTest.php b/tests/Feature/Console/SyncDingWorklogsTest.php index 60bc8de1..71fcee35 100644 --- a/tests/Feature/Console/SyncDingWorklogsTest.php +++ b/tests/Feature/Console/SyncDingWorklogsTest.php @@ -2,8 +2,10 @@ namespace Tests\Feature\Console; +use App\Services\Auth\FinanceRoster; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Carbon; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Mockery; @@ -26,9 +28,12 @@ class SyncDingWorklogsTest extends TestCase 'app.timezone' => 'Asia/Shanghai', 'dingtalk.worklog.enabled' => true, 'dingtalk.worklog.template_name' => '财务日报', + 'dingtalk.worklog.template_names' => ['财务日报'], + 'dingtalk.worklog.finance_only_templates' => ['空白日志'], 'dingtalk.worklog.lookback_days' => 35, ]); DB::purge('business_mirror'); + Cache::flush(); Schema::connection('business_mirror')->create('business_mirror_table_states', function (Blueprint $table): void { $table->string('dataset_key', 191)->primary(); @@ -119,4 +124,75 @@ class SyncDingWorklogsTest extends TestCase Carbon::setTestNow(); } } + + public function test_blank_logs_are_included_only_for_finance_members(): void + { + Carbon::setTestNow(Carbon::parse('2026-11-05 13:00:00', 'Asia/Shanghai')); + config(['dingtalk.worklog.template_names' => ['财务日报', '空白日志']]); + + try { + $client = Mockery::mock(DingTalkWorklogClient::class); + $client->shouldReceive('isConfigured')->once()->andReturnTrue(); + $client->shouldReceive('listReports') + ->once() + ->withArgs(static fn ($from, $to, string $template): bool => $template === '财务日报') + ->andReturn([ + 'pages' => 1, + 'reports' => [[ + 'report_id' => 'finance-daily', + 'creator_id' => 'user-finance-daily', + 'creator_name' => '秋香', + 'template_name' => '财务日报', + 'create_time' => '2026-11-04 22:14:16', + ]], + ]); + $client->shouldReceive('listReports') + ->once() + ->withArgs(static fn ($from, $to, string $template): bool => $template === '空白日志') + ->andReturn([ + 'pages' => 1, + 'reports' => [ + [ + 'report_id' => 'finance-blank-log', + 'creator_id' => 'user-renshen', + 'creator_name' => '人参', + 'template_name' => '空白日志', + 'create_time' => '2026-11-04 23:00:00', + ], + [ + 'report_id' => 'other-department-blank-log', + 'creator_id' => 'user-other', + 'creator_name' => '其他人', + 'template_name' => '空白日志', + 'create_time' => '2026-11-04 23:10:00', + ], + ], + ]); + $this->app->instance(DingTalkWorklogClient::class, $client); + + $roster = Mockery::mock(FinanceRoster::class); + $roster->shouldReceive('cachedFinanceMembers')->once()->andReturn([ + ['userid' => 'user-renshen', 'name' => '人参'], + ]); + $this->app->instance(FinanceRoster::class, $roster); + + $this->artisan('business-mirror:sync-ding-worklogs') + ->expectsOutputToContain('写入/更新 2 条') + ->assertSuccessful(); + + $this->assertSame( + ['finance-blank-log', 'finance-daily'], + DB::connection('business_mirror')->table('ding_worklog_reports') + ->orderBy('report_id')->pluck('report_id')->all(), + ); + $this->assertSame( + '财务日报 / 空白日志', + DB::connection('business_mirror')->table('business_mirror_table_states') + ->where('dataset_key', 'dingtalk.worklog.finance_daily_reports') + ->value('source_object'), + ); + } finally { + Carbon::setTestNow(); + } + } } diff --git a/tests/Feature/Console/SyncJstOrderLabelsDailyTest.php b/tests/Feature/Console/SyncJstOrderLabelsDailyTest.php new file mode 100644 index 00000000..dafb946f --- /dev/null +++ b/tests/Feature/Console/SyncJstOrderLabelsDailyTest.php @@ -0,0 +1,162 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ]]); + DB::purge('business_mirror'); + + Schema::connection('business_mirror')->create('business_mirror_table_states', function ($table): void { + $table->string('dataset_key')->primary(); + $table->string('status')->nullable(); + $table->dateTime('initial_completed_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + }); + Schema::connection('business_mirror')->create('ops_jst_orders', function ($table): void { + $table->integer('Id')->primary(); + $table->bigInteger('o_id')->nullable(); + $table->string('so_id')->nullable(); + $table->string('shop_name')->nullable(); + $table->dateTime('order_date')->nullable(); + $table->text('labels')->nullable(); + $table->text('remark')->nullable(); + }); + Schema::connection('business_mirror')->create('ops_jst_order_item', function ($table): void { + $table->integer('Id')->primary(); + $table->bigInteger('o_id')->nullable(); + $table->string('sku_id')->nullable(); + $table->string('item_status')->nullable(); + }); + DB::connection('business_mirror')->table('business_mirror_table_states')->insert([ + 'dataset_key' => 'operations_replica.rpt.jst_Orders', + 'status' => 'succeeded', + 'initial_completed_at' => '2026-10-01 00:00:00', + 'last_succeeded_at' => '2026-10-04 05:00:00', + ]); + } + + protected function tearDown(): void + { + Carbon::setTestNow(); + parent::tearDown(); + } + + public function test_backfills_missing_history_then_refreshes_recent_days(): void + { + $this->orders([ + ['o_id' => 1, 'so_id' => 'A', 'order_date' => '2026-10-01 10:00:00', 'labels' => '标签甲,标签乙'], + ['o_id' => 2, 'so_id' => 'B', 'order_date' => '2026-10-02 10:00:00', 'labels' => ''], + ['o_id' => 3, 'so_id' => 'C', 'order_date' => '2026-10-03 10:00:00', 'labels' => '标签丙'], + ]); + + $this->artisan('jst-order-labels:sync-daily', [ + '--from' => '2026-10-01', + '--to' => '2026-10-03', + '--company' => $this->company->id, + '--refresh-days' => 1, + '--json' => true, + ])->assertSuccessful(); + + $rows = JstOrderLabel::query()->where('company_id', $this->company->id)->orderBy('id')->get(); + $this->assertCount(4, $rows); + $this->assertSame(['标签甲', '标签乙', '(无标签)', '标签丙'], $rows->pluck('label')->all()); + $this->assertSame(2, $rows->where('order_no', 'A')->count()); + } + + public function test_does_not_pull_new_data_when_history_source_is_missing(): void + { + $this->orders([ + ['o_id' => 3, 'so_id' => 'C', 'order_date' => '2026-10-03 10:00:00', 'labels' => '标签丙'], + ]); + + $this->artisan('jst-order-labels:sync-daily', [ + '--from' => '2026-10-01', + '--to' => '2026-10-03', + '--company' => $this->company->id, + '--refresh-days' => 1, + ])->assertFailed(); + + $this->assertSame(0, JstOrderLabel::query()->where('company_id', $this->company->id)->count()); + } + + public function test_second_run_skips_complete_history_and_only_refreshes_latest_day(): void + { + $this->orders([ + ['o_id' => 1, 'so_id' => 'A', 'order_date' => '2026-10-01 10:00:00', 'labels' => '标签甲'], + ['o_id' => 2, 'so_id' => 'B', 'order_date' => '2026-10-02 10:00:00', 'labels' => '标签乙'], + ]); + + app(JstOrderLabelImporter::class)->import( + '2026-10-01', + '2026-10-01', + $this->company->id, + true, + 'test', + ); + $oldCreatedAt = JstOrderLabel::query()->where('order_no', 'A')->value('created_at')?->toDateTimeString(); + + $this->artisan('jst-order-labels:sync-daily', [ + '--from' => '2026-10-01', + '--to' => '2026-10-02', + '--company' => $this->company->id, + '--refresh-days' => 1, + '--json' => true, + ])->assertSuccessful(); + + $this->assertSame( + $oldCreatedAt, + JstOrderLabel::query()->where('order_no', 'A')->value('created_at')?->toDateTimeString(), + ); + $this->assertSame(1, JstOrderLabel::query()->where('order_no', 'B')->count()); + } + + public function test_refuses_to_run_when_source_mirror_is_not_ready(): void + { + DB::connection('business_mirror')->table('business_mirror_table_states') + ->where('dataset_key', 'operations_replica.rpt.jst_Orders') + ->update(['status' => 'failed']); + $this->orders([ + ['o_id' => 1, 'so_id' => 'A', 'order_date' => '2026-10-01 10:00:00', 'labels' => '标签甲'], + ]); + + $this->artisan('jst-order-labels:sync-daily', [ + '--from' => '2026-10-01', + '--to' => '2026-10-01', + '--company' => $this->company->id, + ])->assertFailed(); + + $this->assertSame(0, JstOrderLabel::query()->where('company_id', $this->company->id)->count()); + } + + private function orders(array $rows): void + { + foreach ($rows as $index => $row) { + DB::connection('business_mirror')->table('ops_jst_orders')->insert([ + 'Id' => $index + 1, + 'o_id' => $row['o_id'], + 'so_id' => $row['so_id'], + 'shop_name' => '测试店铺', + 'order_date' => $row['order_date'], + 'labels' => $row['labels'], + 'remark' => '', + ]); + } + } +} diff --git a/tests/Feature/Settings/NavigationTest.php b/tests/Feature/Settings/NavigationTest.php index cb89c9a8..47515f5c 100644 --- a/tests/Feature/Settings/NavigationTest.php +++ b/tests/Feature/Settings/NavigationTest.php @@ -5,6 +5,7 @@ namespace Tests\Feature\Settings; use App\Models\Auth\Permission; use App\Models\Auth\Role; use App\Utilities\BusinessNavigation; +use App\Utilities\SidebarMenu; use Tests\Feature\FeatureTestCase; class NavigationTest extends FeatureTestCase @@ -278,6 +279,34 @@ class NavigationTest extends FeatureTestCase ->assertSee('/workspace/financial-risk-control/store-violation-alert', false); } + public function testFeeRatioAnomalyMonitoringDirectoryIsAvailable(): void + { + $section = collect(BusinessNavigation::all()) + ->firstWhere('slug', 'fee-ratio-monitoring'); + + $this->assertNotNull($section); + $this->assertSame('费比异常数据监控', $section['title']); + $this->assertSame('monitor_heart', $section['icon']); + $this->assertSame('异常数据监控', $section['pages'][0]['title']); + $this->assertSame('待接入', $section['pages'][0]['directory']['status']); + + $sidebarGroup = collect(SidebarMenu::groups($this->user)) + ->firstWhere('title', '费比异常数据监控'); + $this->assertNotNull($sidebarGroup); + $this->assertSame('fee-ratio-monitoring', $sidebarGroup['items'][0]['section']); + $this->assertSame('overview', $sidebarGroup['items'][0]['page']); + + $this->loginAs() + ->get(route('business.pages.show', [ + 'section' => 'fee-ratio-monitoring', + 'page' => 'overview', + ])) + ->assertOk() + ->assertSeeText('费比异常数据监控') + ->assertSeeText('异常数据监控') + ->assertSeeText('费比异常数据尚未接入'); + } + public function test_business_pages_render_menu_filter_and_open_page_tabs(): void { $this->loginAs() diff --git a/tests/Unit/Auth/FinanceRosterTest.php b/tests/Unit/Auth/FinanceRosterTest.php index 72fa4ca5..487f277b 100644 --- a/tests/Unit/Auth/FinanceRosterTest.php +++ b/tests/Unit/Auth/FinanceRosterTest.php @@ -25,6 +25,34 @@ class FinanceRosterTest extends TestCase $this->assertSame([], $roster->search("张'_%[")); } + public function test_finance_members_are_loaded_from_descendant_departments(): void + { + config(['dingtalk.finance_department_ids' => ['22848291', '994080505']]); + $query = Mockery::mock(UpstreamReadOnlyQuery::class); + $query->shouldReceive('select')->once()->with( + Mockery::on(static function (string $sql): bool { + UpstreamReadOnlyQuery::assertReadOnlySql($sql); + + return str_contains($sql, 'WITH finance_groups') + && str_contains($sql, "Id IN (?,?)") + && str_contains($sql, 'STRING_SPLIT') + && str_contains($sql, "REPLACE(value, '\"', '')"); + }), + ['22848291', '994080505'], + )->andReturn([ + ['userid' => '1001', 'name' => '张宏', 'flowerName' => '人参'], + ['userid' => '1002', 'name' => '吕庭', 'flowerName' => '江陵'], + ]); + $factory = Mockery::mock(UpstreamReadOnlyQueryFactory::class); + $factory->shouldReceive('forSourceWithTimeout') + ->once()->with('operations_replica', 60)->andReturn($query); + + $this->assertSame([ + ['userid' => '1001', 'name' => '人参'], + ['userid' => '1002', 'name' => '江陵'], + ], (new FinanceRoster($factory))->financeMembers()); + } + #[DataProvider('rosterCases')] public function test_roster_authorization(array $overrides, bool $expected): void { diff --git a/tests/Unit/Business/StoreReceiptPlantingDailySynchronizerTest.php b/tests/Unit/Business/StoreReceiptPlantingDailySynchronizerTest.php new file mode 100644 index 00000000..b044aea6 --- /dev/null +++ b/tests/Unit/Business/StoreReceiptPlantingDailySynchronizerTest.php @@ -0,0 +1,108 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ]]); + DB::purge('business_mirror'); + Schema::connection('business_mirror')->create('business_mirror_table_states', function ($table): void { + $table->string('dataset_key')->primary(); + $table->string('status')->nullable(); + $table->dateTime('initial_completed_at')->nullable(); + }); + DB::connection('business_mirror')->table('business_mirror_table_states')->insert([ + 'dataset_key' => 'jiansun.dbo.jst_workOrderInfo', + 'status' => 'succeeded', + 'initial_completed_at' => '2026-10-01 00:00:00', + ]); + } + + public function test_checks_label_coverage_then_syncs_requested_months(): void + { + $coverage = Mockery::mock(JstOrderLabelDailySynchronizer::class); + $coverage->shouldReceive('assertCovered') + ->once() + ->with('2026-10-01', '2026-10-31', 1) + ->andReturn(array_fill(0, 31, ['status' => 'ok'])); + $workOrders = Mockery::mock(PlantingWorkOrderSynchronizer::class); + $workOrders->shouldReceive('sync') + ->once() + ->with('2026-10-01', '2026-10-31', 1) + ->andReturn(['orders' => 10, 'inserted' => 10]); + + $synchronizer = new StoreReceiptPlantingDailySynchronizer( + app(DatabaseManager::class), + $coverage, + $workOrders, + ); + + $result = $synchronizer->sync('2026-10-01', '2026-10-31', 1, ['2026-10']); + + $this->assertSame('ready_to_refresh', $result['status']); + $this->assertSame(['2026-10'], $result['months']); + $this->assertSame(31, $result['checked_days']); + $this->assertSame(10, $result['planting_sync']['2026-10']['orders']); + } + + public function test_defaults_to_current_and_previous_month(): void + { + $coverage = Mockery::mock(JstOrderLabelDailySynchronizer::class); + $coverage->shouldReceive('assertCovered')->once()->andReturn([['status' => 'ok']]); + $workOrders = Mockery::mock(PlantingWorkOrderSynchronizer::class); + $workOrders->shouldReceive('sync') + ->once() + ->with('2026-10-01', '2026-10-31', 1) + ->andReturn([]); + $workOrders->shouldReceive('sync') + ->once() + ->with('2026-11-01', '2026-11-30', 1) + ->andReturn([]); + + $synchronizer = new StoreReceiptPlantingDailySynchronizer( + app(DatabaseManager::class), + $coverage, + $workOrders, + ); + + $result = $synchronizer->sync('2026-10-01', '2026-11-04', 1, ['2026-11', '2026-10']); + + $this->assertSame(['2026-10', '2026-11'], $result['months']); + } + + public function test_blocks_recalculation_when_label_coverage_is_not_ready(): void + { + $coverage = Mockery::mock(JstOrderLabelDailySynchronizer::class); + $coverage->shouldReceive('assertCovered') + ->once() + ->andThrow(new \RuntimeException('历史数据检查未通过')); + $workOrders = Mockery::mock(PlantingWorkOrderSynchronizer::class); + $workOrders->shouldNotReceive('sync'); + + $synchronizer = new StoreReceiptPlantingDailySynchronizer( + app(DatabaseManager::class), + $coverage, + $workOrders, + ); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('历史数据检查未通过'); + $synchronizer->sync('2026-10-01', '2026-10-31', 1, ['2026-10']); + } +} diff --git a/tests/Unit/Deployment/FinanceBatchIsolationTest.php b/tests/Unit/Deployment/FinanceBatchIsolationTest.php index 75a97694..8b3be896 100644 --- a/tests/Unit/Deployment/FinanceBatchIsolationTest.php +++ b/tests/Unit/Deployment/FinanceBatchIsolationTest.php @@ -108,6 +108,90 @@ class FinanceBatchIsolationTest extends TestCase } } + public function test_planting_work_order_sync_uses_the_isolated_import_entry(): void + { + $directory = sys_get_temp_dir() . '/caiwu-planting-import-' . bin2hex(random_bytes(6)); + mkdir($directory); + file_put_contents($directory . '/run-finance-import.py', ''); + file_put_contents( + $directory . '/python3', + '#!/bin/sh' . "\n" . 'printf "%s\n" "$@" > "$CAIWU_CAPTURE"' . "\n", + ); + chmod($directory . '/python3', 0700); + + try { + $process = $this->runBatch($directory, [ + 'planting-details:sync-work-orders', + '--month=2026-10', + ]); + + $this->assertTrue($process->isSuccessful(), $process->getErrorOutput()); + $arguments = file($directory . '/called', FILE_IGNORE_NEW_LINES); + $this->assertContains($directory . '/run-finance-import.py', $arguments); + $this->assertContains('planting-details:sync-work-orders', $arguments); + $this->assertContains('--month=2026-10', $arguments); + } finally { + foreach (glob($directory . '/*') as $path) { + unlink($path); + } + rmdir($directory); + } + } + + public function test_jst_label_daily_sync_uses_the_isolated_import_entry(): void + { + $directory = sys_get_temp_dir() . '/caiwu-jst-label-import-' . bin2hex(random_bytes(6)); + mkdir($directory); + file_put_contents($directory . '/run-finance-import.py', ''); + file_put_contents( + $directory . '/python3', + '#!/bin/sh' . "\n" . 'printf "%s\n" "$@" > "$CAIWU_CAPTURE"' . "\n", + ); + chmod($directory . '/python3', 0700); + + try { + $process = $this->runBatch($directory, [ + 'jst-order-labels:sync-daily', + '--from=2026-10-01', + ]); + + $this->assertTrue($process->isSuccessful(), $process->getErrorOutput()); + $arguments = file($directory . '/called', FILE_IGNORE_NEW_LINES); + $this->assertContains($directory . '/run-finance-import.py', $arguments); + $this->assertContains('jst-order-labels:sync-daily', $arguments); + } finally { + foreach (glob($directory . '/*') as $path) { + unlink($path); + } + rmdir($directory); + } + } + + public function test_planting_daily_uses_the_isolated_batch_profile(): void + { + $directory = sys_get_temp_dir() . '/caiwu-planting-daily-' . bin2hex(random_bytes(6)); + mkdir($directory); + try { + $arguments = [ + 'store-receipt:planting-daily', + '--from=2026-10-01', + '--company=1', + ]; + $process = $this->runBatch($directory, $arguments); + + $this->assertTrue($process->isSuccessful(), $process->getErrorOutput()); + $called = file($directory . '/called', FILE_IGNORE_NEW_LINES); + $this->assertContains('batch', $called); + $this->assertContains('--no-deps', $called); + $this->assertSame($arguments, array_slice($called, -count($arguments))); + } finally { + foreach (glob($directory . '/*') as $path) { + unlink($path); + } + rmdir($directory); + } + } + public function test_business_mirror_history_backfill_runs_in_the_isolated_batch_profile(): void { $directory = sys_get_temp_dir() . '/caiwu-mirror-batch-' . bin2hex(random_bytes(6)); diff --git a/tests/Unit/Deployment/FinanceImportRuntimeTest.php b/tests/Unit/Deployment/FinanceImportRuntimeTest.php index 81c0afbc..420d6023 100644 --- a/tests/Unit/Deployment/FinanceImportRuntimeTest.php +++ b/tests/Unit/Deployment/FinanceImportRuntimeTest.php @@ -51,6 +51,19 @@ class FinanceImportRuntimeTest extends TestCase (new RequireImportBatchContainer())->handle($this->starting('product:monthly-weighted-average:base')); } + public function test_work_order_sync_is_registered_as_a_protected_import(): void + { + config([ + 'finance_batch.import_commands' => [ + 'planting-details:sync-work-orders', + ], + ]); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('run-finance-batch.sh'); + (new RequireImportBatchContainer())->handle($this->starting('planting-details:sync-work-orders')); + } + public function test_production_batch_runtime_can_import_and_health_checks_stay_available(): void { $listener = new RequireImportBatchContainer(); diff --git a/tests/Unit/EcommerceFinance/DingWorklogPenaltyCalculatorTest.php b/tests/Unit/EcommerceFinance/DingWorklogPenaltyCalculatorTest.php new file mode 100644 index 00000000..0227a75d --- /dev/null +++ b/tests/Unit/EcommerceFinance/DingWorklogPenaltyCalculatorTest.php @@ -0,0 +1,94 @@ + '2026-10-10', + 'app.timezone' => 'Asia/Shanghai', + ]); + $submitted = []; + $misses = [ + 'jiangling' => ['2026-10-10', '2026-10-12', '2026-10-18'], + 'qiuxiang' => ['2026-10-12', '2026-10-18'], + ]; + foreach (['jiangling' => '江陵', 'qiuxiang' => '秋香'] as $userId => $name) { + for ($day = 10; $day <= 18; $day++) { + $date = sprintf('2026-10-%02d', $day); + if (! in_array($date, $misses[$userId], true)) { + $submitted[] = [ + 'creator_userid' => $userId, + 'creator_name' => $name, + 'statistics_date' => $date, + ]; + } + } + } + + $repository = Mockery::mock(DingWorklogMirrorRepository::class); + $repository->shouldReceive('earliestStatisticsDate')->once()->andReturn('2026-10-01'); + $repository->shouldReceive('submittedDatesByUser') + ->once()->with('2026-10-10', '2026-10-18')->andReturn($submitted); + $roster = Mockery::mock(FinanceRoster::class); + $roster->shouldReceive('cachedFinanceMembers')->once()->andReturn([ + ['userid' => 'jiangling', 'name' => '江陵'], + ['userid' => 'qiuxiang', 'name' => '秋香'], + ]); + + $result = (new DingWorklogPenaltyCalculator($repository, $roster))->summary( + '2026-10-10', + '2026-10-18', + Carbon::parse('2026-10-20 10:00:00', 'Asia/Shanghai'), + ); + + $this->assertSame('2026-10-10', $result['start_date']); + $this->assertSame('2026-10-18', $result['end_date']); + $this->assertSame('江陵', $result['members'][0]['name']); + $this->assertSame(['2026-10-10', '2026-10-12', '2026-10-18'], $result['members'][0]['missed_dates']); + $this->assertSame(3, $result['members'][0]['missed_count']); + $this->assertSame('10 + 20 + 40', $result['members'][0]['penalty_formula']); + $this->assertSame('70', $result['members'][0]['penalty_points']); + $this->assertSame('秋香', $result['members'][1]['name']); + $this->assertSame('10 + 20', $result['members'][1]['penalty_formula']); + $this->assertSame('30', $result['members'][1]['penalty_points']); + $this->assertSame('100', $result['total_points']); + $this->assertSame('100', $result['total_points_formatted']); + } + + public function test_dates_before_november_fourth_are_not_charged(): void + { + config([ + 'dingtalk.worklog.penalty_start_date' => '2026-11-04', + 'app.timezone' => 'Asia/Shanghai', + ]); + $repository = Mockery::mock(DingWorklogMirrorRepository::class); + $repository->shouldReceive('earliestStatisticsDate')->once()->andReturn('2026-10-21'); + $repository->shouldReceive('submittedDatesByUser') + ->once()->with('2026-11-04', '2026-11-04')->andReturn([]); + $roster = Mockery::mock(FinanceRoster::class); + $roster->shouldReceive('cachedFinanceMembers')->once()->andReturn([ + ['userid' => 'jiangling', 'name' => '江陵'], + ]); + + $result = (new DingWorklogPenaltyCalculator($repository, $roster))->summary( + '2026-10-22', + '2026-11-04', + Carbon::parse('2026-11-05 13:00:00', 'Asia/Shanghai'), + ); + + $this->assertSame('2026-11-04', $result['start_date']); + $this->assertSame('2026-11-04', $result['end_date']); + $this->assertSame(['2026-11-04'], $result['members'][0]['missed_dates']); + $this->assertSame('10', $result['total_points']); + } +} diff --git a/tests/Unit/EcommerceFinance/DingWorklogStatisticsPageDataTest.php b/tests/Unit/EcommerceFinance/DingWorklogStatisticsPageDataTest.php new file mode 100644 index 00000000..62b5ecef --- /dev/null +++ b/tests/Unit/EcommerceFinance/DingWorklogStatisticsPageDataTest.php @@ -0,0 +1,58 @@ +shouldReceive('available')->andReturnTrue(); + $repository->shouldReceive('state')->once()->andReturn([ + 'status' => 'succeeded', + 'last_attempted_at' => '2026-11-05 12:45:00', + 'last_succeeded_at' => '2026-11-05 12:45:00', + 'mirror_row_count' => 83, + 'last_error_code' => null, + ]); + $repository->shouldReceive('dailySummary')->once()->andReturn([[ + 'statistics_date' => '2026-11-04', + 'submission_count' => 9, + 'submitter_count' => 9, + 'first_submitted_at' => '2026-11-04 20:16:55', + 'last_submitted_at' => '2026-11-05 11:32:59', + ]]); + $repository->shouldNotReceive('submissionsForDate'); + + $penalty = Mockery::mock(DingWorklogPenaltyCalculator::class); + $penalty->shouldReceive('summary')->once()->andReturn([ + 'start_date' => '2026-11-04', + 'end_date' => '2026-11-04', + 'total_points' => '40', + 'total_points_formatted' => '40', + 'members' => [], + ]); + + $data = (new DingWorklogStatisticsPageData($repository, $penalty))->page( + Request::create('/?from=2026-10-22&to=2026-11-04') + ); + + $this->assertFalse($data['worklogShowDetails']); + $this->assertSame([], $data['worklogSubmissions']); + $this->assertSame(9, $data['worklogDaily'][0]['submitter_count']); + } finally { + Carbon::setTestNow(); + } + } +} diff --git a/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php b/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php index 33946b33..55155552 100644 --- a/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php @@ -56,6 +56,7 @@ class TaobaoAlipaySettlementBillRepositoryTest extends TestCase $this->assertSame(15.0, $result['summary']['expense']); $this->assertSame(230.0, $result['summary']['opening_balance']); $this->assertSame('2026-09-30', $result['summary']['opening_balance_date']); + $this->assertSame('previous_period', $result['summary']['opening_balance_source']); $this->assertSame(275.0, $result['summary']['balance']); } @@ -84,6 +85,32 @@ class TaobaoAlipaySettlementBillRepositoryTest extends TestCase $this->assertSame(180.0, $result['summary']['balance']); } + public function test_first_imported_month_infers_opening_balance_from_first_account_rows(): void + { + $rows = DB::connection('business_mirror')->table('taobao_alipay_bill_rows'); + $rows->insert([ + $this->row('A-JUL-1', '天猫-A店', 'account-a', '2026-07-01 09:00:00', 10, 0, 210, 10), + $this->row('A-JUL-2', '天猫-A店', 'account-a', '2026-07-02 09:00:00', 20, 5, 225, 20), + $this->row('B-JUL-1', '淘宝-B店', 'account-b', '2026-07-01 10:00:00', 0, 10, 90, 30), + $this->row('B-JUL-2', '淘宝-B店', 'account-b', '2026-07-03 10:00:00', 5, 0, 95, 40), + ]); + + $result = app(TaobaoAlipaySettlementBillRepository::class)->paginate( + ['start' => '2026-07-01', 'end' => '2026-07-31'], + 'occurred_at', + 'desc', + 1, + 20, + ); + + // A 首笔倒推期初 200,B 首笔倒推期初 100。 + $this->assertSame(300.0, $result['summary']['opening_balance']); + $this->assertSame('first_row_estimate', $result['summary']['opening_balance_source']); + $this->assertSame(35.0, $result['summary']['income']); + $this->assertSame(15.0, $result['summary']['expense']); + $this->assertSame(320.0, $result['summary']['balance']); + } + private function createTables(): void { $schema = Schema::connection('business_mirror');