From 557e56273e98b9fbda26657baeab7a8d067d091b Mon Sep 17 00:00:00 2001 From: huilan <2430273709@qq.com> Date: Wed, 18 Nov 2026 15:14:12 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=91=E7=A5=A8=E9=A2=9D=E5=BA=A6?= =?UTF-8?q?=E8=AF=BB=E5=8F=96=E7=A5=A8=E8=81=9A=E9=94=80=E6=96=B9=E5=8F=AF?= =?UTF-8?q?=E7=94=A8=E9=A2=9D=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Business/InvoiceQuotaPageData.php | 233 +++++++++++------- .../Piaoju/PiaojuSellerQuotaClient.php | 170 +++++++++++++ .../Piaoju/PiaojuSellerQuotaImporter.php | 128 ++++++++++ .../Piaoju/PiaojuSellerQuotaRepository.php | 57 +++++ .../Commands/SyncPiaojuSellerQuotas.php | 81 ++++++ app/Console/Kernel.php | 12 + config/business_data.php | 5 + config/piaoju.php | 13 + ...0_create_piaoju_seller_quota_snapshots.php | 51 ++++ docs/上游业务镜像清单.md | 1 + .../business/pages/invoice_quota.blade.php | 77 ++---- .../Feature/Business/InvoiceQuotaPageTest.php | 65 ++++- .../Business/PiaojuSellerQuotaSyncTest.php | 115 +++++++++ 13 files changed, 853 insertions(+), 155 deletions(-) create mode 100644 app/Business/Piaoju/PiaojuSellerQuotaClient.php create mode 100644 app/Business/Piaoju/PiaojuSellerQuotaImporter.php create mode 100644 app/Business/Piaoju/PiaojuSellerQuotaRepository.php create mode 100644 app/Console/Commands/SyncPiaojuSellerQuotas.php create mode 100644 config/piaoju.php create mode 100644 database/migrations/2026_11_18_120000_create_piaoju_seller_quota_snapshots.php create mode 100644 tests/Feature/Business/PiaojuSellerQuotaSyncTest.php diff --git a/app/Business/InvoiceQuotaPageData.php b/app/Business/InvoiceQuotaPageData.php index ea1d8ecc..f39d0884 100644 --- a/app/Business/InvoiceQuotaPageData.php +++ b/app/Business/InvoiceQuotaPageData.php @@ -2,15 +2,21 @@ namespace App\Business; +use App\Business\Piaoju\PiaojuSellerQuotaRepository; use App\Models\Business\InvoiceBasic; use Illuminate\Pagination\LengthAwarePaginator; +use Illuminate\Support\Carbon; +use Illuminate\Support\Collection; use Throwable; class InvoiceQuotaPageData { private const PER_PAGE = 50; - private const WARNING_RATE = 0.8; + public function __construct( + private readonly PiaojuSellerQuotaRepository $piaojuQuotas, + ) { + } public function page(): array { @@ -37,70 +43,75 @@ class InvoiceQuotaPageData 100 ); - $filtered = InvoiceBasic::query(); + $query = InvoiceBasic::query()->select([ + 'id', + 'store_name', + 'store_entity', + 'invoice_issuer', + 'invoice_limit', + 'output_amount', + 'period', + ]); if ($period !== '') { - $filtered->where('period', $period); + $query->where('period', $period); } else { - $filtered->where(function ($query): void { + $query->where(function ($query): void { $query->whereNull('period')->orWhere('period', ''); }); } if ($sellerEntity !== '') { $needle = '%' . addcslashes($sellerEntity, '%_\\') . '%'; - $filtered->where('store_entity', 'like', $needle); + $query->where('store_entity', 'like', $needle); } - $aggregate = (clone $filtered) - ->reorder() - ->selectRaw( - 'COUNT(*) AS record_count, - COALESCE(SUM(invoice_limit), 0) AS quota_total, - COALESCE(SUM(output_amount), 0) AS used_total, - SUM(CASE WHEN output_amount > invoice_limit THEN 1 ELSE 0 END) AS exceeded_count, - SUM(CASE WHEN invoice_limit > 0 - AND output_amount > 0 - AND output_amount <= invoice_limit - AND output_amount >= invoice_limit * ? THEN 1 ELSE 0 END) AS warning_count', - [self::WARNING_RATE] - ) - ->first(); - - $rows = (clone $filtered) - ->select([ - 'id', - 'store_name', - 'store_entity', - 'invoice_issuer', - 'invoice_limit', - 'output_amount', - 'period', - ]) - ->orderByRaw( - 'CASE - WHEN output_amount > invoice_limit THEN 0 - WHEN invoice_limit > 0 AND output_amount >= invoice_limit * ? THEN 1 - WHEN invoice_limit > 0 THEN 2 - ELSE 3 - END', - [self::WARNING_RATE] - ) + $snapshots = $this->piaojuQuotas->byNormalizedName(); + $rows = $query ->orderBy('store_entity') ->orderByDesc('id') - ->paginate(self::PER_PAGE) - ->withQueryString(); + ->get() + ->map(fn (InvoiceBasic $row): object => $this->presentRow( + $row, + $snapshots->get(PiaojuSellerQuotaRepository::normalizeName((string) $row->store_entity)) + )) + ->sortBy(static fn (object $row): string => sprintf( + '%02d|%s', + $row->status_rank, + (string) $row->store_entity + )) + ->values(); - $rows->setCollection( - $rows->getCollection()->map( - fn (InvoiceBasic $row): object => $this->presentRow($row) - ) + $total = $rows->count(); + $lastPage = max(1, (int) ceil($total / self::PER_PAGE)); + $currentPage = min(max((int) request()->query('page', 1), 1), $lastPage); + $pageRows = $rows + ->slice(($currentPage - 1) * self::PER_PAGE, self::PER_PAGE) + ->values(); + + $paginator = new LengthAwarePaginator( + $pageRows, + $total, + self::PER_PAGE, + $currentPage, + [ + 'path' => request()->url(), + 'query' => request()->query(), + ] ); - $quotaTotal = round((float) ($aggregate->quota_total ?? 0), 2); - $usedTotal = round((float) ($aggregate->used_total ?? 0), 2); - $exceededCount = (int) ($aggregate->exceeded_count ?? 0); - $warningCount = (int) ($aggregate->warning_count ?? 0); + $quotaTotal = round($rows->sum(static fn (object $row): float => (float) $row->invoice_limit), 2); + $usedTotal = round($rows->sum(static fn (object $row): float => (float) $row->output_amount), 2); + $availableRows = $rows->filter( + static fn (object $row): bool => $row->available_amount !== null + ); + $availableTotal = round($availableRows->sum( + static fn (object $row): float => (float) $row->available_amount + ), 2); + $matchedCount = $rows->where('snapshot_matched', true)->count(); + $unmatchedCount = $rows->where('snapshot_matched', false)->count(); + $unavailableCount = $rows->where('snapshot_unavailable', true)->count(); + $insufficientCount = $rows->where('insufficient', true)->count(); return [ 'view' => 'business.pages.invoice_quota', @@ -108,20 +119,23 @@ class InvoiceQuotaPageData 'period' => $period, 'periodOptions' => $periodOptions, 'sellerEntity' => $sellerEntity, - 'rows' => $rows, + 'rows' => $paginator, 'summary' => [ - 'record_count' => (int) ($aggregate->record_count ?? 0), + 'record_count' => $total, 'quota_total' => $quotaTotal, 'used_total' => $usedTotal, - 'remaining_total' => round($quotaTotal - $usedTotal, 2), - 'usage_rate' => $quotaTotal > 0 - ? round($usedTotal / $quotaTotal * 100, 1) - : null, - 'exceeded_count' => $exceededCount, - 'warning_count' => $warningCount, - 'attention_count' => $exceededCount + $warningCount, + 'available_total' => $availableTotal, + 'matched_count' => $matchedCount, + 'unmatched_count' => $unmatchedCount, + 'unavailable_count' => $unavailableCount, + 'insufficient_count' => $insufficientCount, + 'latest_quota_updated_at' => $this->latestDateTime( + $rows->pluck('quota_updated_at') + ), + 'latest_source_fetched_at' => $this->latestDateTime( + $rows->pluck('source_fetched_at') + ), ], - 'warningRate' => self::WARNING_RATE * 100, 'loadError' => null, ]; } catch (Throwable $exception) { @@ -131,29 +145,45 @@ class InvoiceQuotaPageData } } - private function presentRow(InvoiceBasic $row): object + private function presentRow(InvoiceBasic $row, ?object $snapshot): object { - $quota = round((float) $row->invoice_limit, 2); - $used = round((float) $row->output_amount, 2); - $remaining = round($quota - $used, 2); - $usageRate = $quota > 0 ? round($used / $quota * 100, 1) : null; + $invoiceLimit = round((float) $row->invoice_limit, 2); + $outputAmount = round((float) $row->output_amount, 2); + $availableAmount = $snapshot !== null && is_numeric($snapshot->invoice_limit) + ? round((float) $snapshot->invoice_limit, 2) + : null; + $authStatus = strtoupper(trim((string) ($snapshot->auth_status ?? ''))); - if ($used > $quota) { - $status = '超额'; + if ($snapshot === null) { + $status = '未匹配'; + $statusTone = 'muted'; + $statusIcon = 'link_off'; + $statusRank = 0; + } elseif ($authStatus === 'AUTHENTICATED_EXPIRED') { + $status = '授权过期'; + $statusTone = 'warning'; + $statusIcon = 'schedule'; + $statusRank = 1; + } elseif ($authStatus !== 'AUTHENTICATED') { + $status = '不可查看'; + $statusTone = 'muted'; + $statusIcon = 'visibility_off'; + $statusRank = 1; + } elseif ($availableAmount === null) { + $status = '未获取额度'; + $statusTone = 'muted'; + $statusIcon = 'cloud_off'; + $statusRank = 1; + } elseif ($availableAmount <= 0) { + $status = '额度不足'; $statusTone = 'danger'; $statusIcon = 'error'; - } elseif ($quota <= 0) { - $status = '未设置额度'; - $statusTone = 'muted'; - $statusIcon = 'remove_circle_outline'; - } elseif ($usageRate !== null && $usageRate >= self::WARNING_RATE * 100) { - $status = '需关注'; - $statusTone = 'warning'; - $statusIcon = 'warning_amber'; + $statusRank = 2; } else { $status = '正常'; $statusTone = 'success'; $statusIcon = 'check_circle_outline'; + $statusRank = 3; } return (object) [ @@ -161,20 +191,48 @@ class InvoiceQuotaPageData 'store_name' => $row->store_name, 'store_entity' => $row->store_entity, 'invoice_issuer' => $row->invoice_issuer, - 'invoice_limit' => $quota, - 'output_amount' => $used, - 'remaining' => $remaining, - 'usage_rate' => $usageRate, - 'usage_bar_width' => $usageRate === null - ? 0 - : min(100, max(0, (int) round($usageRate))), + 'invoice_limit' => $invoiceLimit, + 'output_amount' => $outputAmount, + 'available_amount' => $availableAmount, + 'quota_updated_at' => $this->formatDateTime($snapshot->invoice_limit_updated_at ?? null), + 'source_fetched_at' => $this->formatDateTime($snapshot->source_fetched_at ?? null), + 'snapshot_matched' => $snapshot !== null, + 'snapshot_unavailable' => $snapshot !== null + && ($authStatus !== 'AUTHENTICATED' || $availableAmount === null), + 'insufficient' => $snapshot !== null + && $authStatus === 'AUTHENTICATED' + && $availableAmount !== null + && $availableAmount <= 0, 'status' => $status, 'status_tone' => $statusTone, 'status_icon' => $statusIcon, + 'status_rank' => $statusRank, 'period' => $row->period, ]; } + private function formatDateTime(mixed $value): ?string + { + $text = trim((string) ($value ?? '')); + if ($text === '') { + return null; + } + + try { + return Carbon::parse($text, 'Asia/Shanghai')->format('Y-m-d H:i'); + } catch (Throwable) { + return null; + } + } + + private function latestDateTime(Collection $values): ?string + { + return $values + ->filter(static fn (mixed $value): bool => trim((string) $value) !== '') + ->sortDesc() + ->first(); + } + private function normalizePeriod(string $period): ?string { return preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1 @@ -198,13 +256,14 @@ class InvoiceQuotaPageData 'record_count' => 0, 'quota_total' => 0.0, 'used_total' => 0.0, - 'remaining_total' => 0.0, - 'usage_rate' => null, - 'exceeded_count' => 0, - 'warning_count' => 0, - 'attention_count' => 0, + 'available_total' => 0.0, + 'matched_count' => 0, + 'unmatched_count' => 0, + 'unavailable_count' => 0, + 'insufficient_count' => 0, + 'latest_quota_updated_at' => null, + 'latest_source_fetched_at' => null, ], - 'warningRate' => self::WARNING_RATE * 100, 'loadError' => '发票额度数据暂时无法读取,请稍后重试。', ]; } diff --git a/app/Business/Piaoju/PiaojuSellerQuotaClient.php b/app/Business/Piaoju/PiaojuSellerQuotaClient.php new file mode 100644 index 00000000..49ea33e7 --- /dev/null +++ b/app/Business/Piaoju/PiaojuSellerQuotaClient.php @@ -0,0 +1,170 @@ +> + */ + public function fetchAll(): array + { + $this->prepare(); + + $rows = []; + $total = null; + $pageSize = max((int) config('piaoju.page_size', 100), 1); + $maxPages = max((int) config('piaoju.max_pages', 20), 1); + + for ($page = 1; $page <= $maxPages; $page++) { + [$batch, $pageTotal] = $this->fetchPage($page, $pageSize); + $total ??= $pageTotal; + + foreach ($batch as $row) { + if (! is_array($row)) { + continue; + } + + $key = trim((string) ($row['id'] ?? $row['sellerCode'] ?? '')); + if ($key === '') { + throw new RuntimeException('piaoju_seller_key_missing'); + } + $rows[$key] = $row; + } + + if ($batch === [] + || ($total !== null && count($rows) >= $total) + || ($total === null && count($batch) < $pageSize)) { + break; + } + } + + if ($total !== null && count($rows) !== $total) { + throw new RuntimeException('piaoju_seller_count_mismatch'); + } + + return array_values($rows); + } + + /** + * @return array{0:list>,1:?int} + */ + private function fetchPage(int $page, int $pageSize): array + { + $response = Http::acceptJson() + ->withHeaders([ + 'Cookie' => $this->cookieHeader(), + 'Origin' => 'https://fp.erp321.com', + 'Referer' => 'https://fp.erp321.com/setting/companyBodyManage', + 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' + . '(KHTML, like Gecko) Chrome/157.0.0.0 Safari/537.36 Edg/157.0.0.0', + ]) + ->connectTimeout(10) + ->timeout(max((int) config('piaoju.timeout_seconds', 30), 1)) + ->retry(2, 300, throw: false) + ->post( + rtrim((string) config('piaoju.api_base_url'), '/') . '/fp/fms/company/seller/page', + [ + 'data' => [ + 'coid' => (string) config('piaoju.coid'), + 'uid' => (string) config('piaoju.uid'), + 'ssProjectType' => (string) config('piaoju.project_type'), + 'sellerNames' => [], + 'status' => null, + 'authStatus' => null, + ], + 'page' => [ + 'pageNum' => $page, + 'pageSize' => $pageSize, + ], + ] + ); + + return $this->parseResponse($response); + } + + /** + * @return array{0:list>,1:?int} + */ + private function parseResponse(Response $response): array + { + if (! $response->successful()) { + throw new RuntimeException('piaoju_api_http_error'); + } + + $payload = $response->json(); + if (! is_array($payload)) { + throw new RuntimeException('piaoju_api_invalid_response'); + } + + $code = $payload['code'] ?? null; + if ($code !== null && ! in_array((string) $code, ['0', '0000', '200'], true)) { + throw new RuntimeException( + in_array((string) $code, ['-1', '1006', '403'], true) + ? 'piaoju_api_auth_failed' + : 'piaoju_api_error' + ); + } + + if (($payload['success'] ?? null) === false) { + throw new RuntimeException('piaoju_api_error'); + } + + $data = $payload['data'] ?? null; + $rows = null; + $total = null; + + if (is_array($data)) { + if (array_is_list($data)) { + $rows = $data; + $total = isset($payload['total']) ? (int) $payload['total'] : null; + } else { + $rows = $data['list'] ?? $data['records'] ?? null; + $total = $data['total'] ?? $payload['total'] ?? null; + } + } + + if (! is_array($rows)) { + throw new RuntimeException('piaoju_api_invalid_response'); + } + + return [ + array_values(array_filter($rows, 'is_array')), + $total === null ? null : max((int) $total, 0), + ]; + } + + private function prepare(): void + { + $this->cookieHeader(); + + if (trim((string) config('piaoju.coid')) === '' + || trim((string) config('piaoju.uid')) === '') { + throw new RuntimeException('piaoju_api_context_missing'); + } + } + + private function cookieHeader(): string + { + $cookie = trim((string) config('piaoju.cookie', '')); + if ($cookie !== '') { + return $cookie; + } + + $path = trim((string) config('piaoju.cookie_file', '')); + if ($path === '' || ! is_file($path)) { + throw new RuntimeException('piaoju_cookie_not_configured'); + } + + $cookie = trim((string) file_get_contents($path)); + if ($cookie === '' || preg_match('/[\r\n]/', $cookie) === 1) { + throw new RuntimeException('piaoju_cookie_invalid'); + } + + return $cookie; + } +} diff --git a/app/Business/Piaoju/PiaojuSellerQuotaImporter.php b/app/Business/Piaoju/PiaojuSellerQuotaImporter.php new file mode 100644 index 00000000..1fab2b2f --- /dev/null +++ b/app/Business/Piaoju/PiaojuSellerQuotaImporter.php @@ -0,0 +1,128 @@ +> $rows + */ + public function replace(array $rows, ?DateTimeInterface $fetchedAt = null): int + { + $values = $this->values($rows, $fetchedAt); + if ($values === []) { + throw new RuntimeException('piaoju_seller_rows_empty'); + } + + $connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')); + $connection->beginTransaction(); + try { + foreach (array_chunk($values, 200) as $chunk) { + $connection->table(self::TABLE)->upsert( + $chunk, + ['seller_key'], + [ + 'seller_name', + 'tax_number', + 'seller_status', + 'auth_status', + 'auth_status_desc', + 'invoice_limit', + 'invoice_limit_updated_at', + 'source_fetched_at', + 'synced_at', + 'updated_at', + ], + ); + } + + $connection->table(self::TABLE) + ->whereNotIn('seller_key', array_column($values, 'seller_key')) + ->delete(); + $connection->commit(); + } catch (Throwable $exception) { + $connection->rollBack(); + throw $exception; + } + + return count($values); + } + + /** + * @param list> $rows + * @return list> + */ + public function values(array $rows, ?DateTimeInterface $fetchedAt = null): array + { + $fetchedAt ??= now(); + $sourceFetchedAt = Carbon::instance($fetchedAt) + ->setTimezone('Asia/Shanghai') + ->format('Y-m-d H:i:s'); + $values = []; + + foreach ($rows as $row) { + $taxNumber = $this->text($row['taxNumber'] ?? null, 64); + $sellerKey = $taxNumber + ?? trim((string) ($row['id'] ?? $row['sellerCode'] ?? '')); + $sellerName = trim((string) ($row['sellerName'] ?? '')); + if ($sellerKey === '' || $sellerName === '') { + throw new RuntimeException('piaoju_seller_row_invalid'); + } + + if (isset($values[$sellerKey])) { + throw new RuntimeException('piaoju_seller_key_duplicated'); + } + + $values[$sellerKey] = [ + 'seller_key' => mb_substr($sellerKey, 0, 64), + 'seller_name' => mb_substr($sellerName, 0, 191), + 'tax_number' => $taxNumber, + 'seller_status' => $row['status'] === null ? null : (bool) $row['status'], + 'auth_status' => $this->text($row['authStatus'] ?? null, 32), + 'auth_status_desc' => $this->text($row['authStatusDesc'] ?? null, 64), + 'invoice_limit' => $this->decimal($row['invoiceLimit'] ?? null), + 'invoice_limit_updated_at' => $this->dateTime($row['invoiceLimitUpdated'] ?? null), + 'source_fetched_at' => $sourceFetchedAt, + 'synced_at' => now(), + 'created_at' => now(), + 'updated_at' => now(), + ]; + } + + return array_values($values); + } + + private function text(mixed $value, int $length): ?string + { + $text = trim((string) ($value ?? '')); + + return $text === '' ? null : mb_substr($text, 0, $length); + } + + private function decimal(mixed $value): ?float + { + return is_numeric($value) ? round((float) $value, 2) : null; + } + + private function dateTime(mixed $value): ?string + { + $text = trim((string) ($value ?? '')); + if ($text === '') { + return null; + } + + try { + return Carbon::parse($text, 'Asia/Shanghai')->format('Y-m-d H:i:s'); + } catch (Throwable) { + return null; + } + } +} diff --git a/app/Business/Piaoju/PiaojuSellerQuotaRepository.php b/app/Business/Piaoju/PiaojuSellerQuotaRepository.php new file mode 100644 index 00000000..00fa3478 --- /dev/null +++ b/app/Business/Piaoju/PiaojuSellerQuotaRepository.php @@ -0,0 +1,57 @@ + + */ + public function byNormalizedName(): Collection + { + try { + $connectionName = (string) config('upstream_mirrors.connection', 'business_mirror'); + if (! Schema::connection($connectionName)->hasTable(PiaojuSellerQuotaImporter::TABLE)) { + return collect(); + } + + $rows = DB::connection($connectionName) + ->table(PiaojuSellerQuotaImporter::TABLE) + ->select([ + 'seller_key', + 'seller_name', + 'tax_number', + 'seller_status', + 'auth_status', + 'auth_status_desc', + 'invoice_limit', + 'invoice_limit_updated_at', + 'source_fetched_at', + 'synced_at', + ]) + ->get(); + + return $rows + ->groupBy(fn (object $row): string => self::normalizeName((string) $row->seller_name)) + ->filter(fn (Collection $group): bool => $group->count() === 1) + ->map(static fn (Collection $group): object => $group->first()); + } catch (Throwable $exception) { + report($exception); + + return collect(); + } + } + + public static function normalizeName(string $name): string + { + $name = str_replace(['(', ')'], ['(', ')'], trim($name)); + $name = preg_replace('/\s+/u', '', $name) ?? $name; + + return mb_strtoupper($name); + } +} diff --git a/app/Console/Commands/SyncPiaojuSellerQuotas.php b/app/Console/Commands/SyncPiaojuSellerQuotas.php new file mode 100644 index 00000000..e1d73507 --- /dev/null +++ b/app/Console/Commands/SyncPiaojuSellerQuotas.php @@ -0,0 +1,81 @@ +inputRows($client); + $values = $importer->values($rows); + + if ((bool) $this->option('dry-run')) { + $this->info(sprintf('票聚销方额度读取成功:%d 条,未写入镜像。', count($values))); + + return self::SUCCESS; + } + + $written = $importer->replace($rows); + } catch (Throwable $exception) { + report($exception); + $this->error('票聚销方额度同步失败,已保留上一版镜像。'); + + return self::FAILURE; + } + + $this->info(sprintf('票聚销方额度同步完成:%d 条。', $written)); + + return self::SUCCESS; + } + + /** + * @return list> + */ + private function inputRows(PiaojuSellerQuotaClient $client): array + { + $fromStdin = (bool) $this->option('stdin'); + $path = trim((string) $this->option('file')); + if (! $fromStdin && $path === '') { + return $client->fetchAll(); + } + + $raw = $fromStdin ? stream_get_contents(STDIN) : file_get_contents($path); + if (! is_string($raw) || trim($raw) === '') { + throw new \RuntimeException('piaoju_input_empty'); + } + + $decoded = json_decode($raw, true, 512, JSON_THROW_ON_ERROR); + $rows = null; + if (is_array($decoded)) { + if (array_is_list($decoded)) { + $rows = $decoded; + } else { + $data = $decoded['data'] ?? null; + if (is_array($data)) { + $rows = array_is_list($data) + ? $data + : ($data['list'] ?? $data['records'] ?? null); + } + } + } + + if (! is_array($rows)) { + throw new \RuntimeException('piaoju_input_invalid'); + } + + return array_values(array_filter($rows, 'is_array')); + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 160e6ac0..f25138da 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -140,6 +140,18 @@ class Kernel extends ConsoleKernel ->appendOutputTo(storage_path('logs/ding-attendance-sync.log')) ->runInBackground(); + // 票聚销方管理的可用发票额度按 15 分钟同步到共享镜像;失败时页面继续使用上一版。 + $piaojuCookieFile = trim((string) config('piaoju.cookie_file', '')); + if (trim((string) config('piaoju.cookie', '')) !== '' + || ($piaojuCookieFile !== '' && is_file($piaojuCookieFile))) { + $schedule->command('piaoju:sync-invoice-quotas --quiet') + ->cron('*/15 * * * *') + ->timezone('Asia/Shanghai') + ->withoutOverlapping(15) + ->appendOutputTo(storage_path('logs/piaoju-invoice-quota-sync.log')) + ->runInBackground(); + } + if ((bool) config('services.esign.polling_enabled', false)) { $schedule->command('esign:poll-signatures --quiet') ->cron('*/2 * * * *') diff --git a/config/business_data.php b/config/business_data.php index 753d0062..82869b64 100644 --- a/config/business_data.php +++ b/config/business_data.php @@ -170,6 +170,11 @@ return [ ], 'special_tables' => [ + 'piaoju_seller_quota_snapshots' => [ + 'role' => 'dimension', + 'target_store' => 'mariadb', + 'consumer' => '发票额度·票聚销方可用额度', + ], 'store_report_bill_rows' => [ 'role' => 'fact', 'target_store' => 'clickhouse', diff --git a/config/piaoju.php b/config/piaoju.php new file mode 100644 index 00000000..cb799a40 --- /dev/null +++ b/config/piaoju.php @@ -0,0 +1,13 @@ + rtrim((string) env('PIAOJU_API_BASE_URL', 'https://api.erp321.com'), '/'), + 'coid' => (string) env('PIAOJU_COID', '10048510'), + 'uid' => (string) env('PIAOJU_UID', '21667'), + 'project_type' => (string) env('PIAOJU_PROJECT_TYPE', 'SSPJ'), + 'cookie' => env('PIAOJU_COOKIE'), + 'cookie_file' => env('PIAOJU_COOKIE_FILE', base_path('runtime/private/piaoju-cookie.txt')), + 'page_size' => 100, + 'max_pages' => 20, + 'timeout_seconds' => 30, +]; diff --git a/database/migrations/2026_11_18_120000_create_piaoju_seller_quota_snapshots.php b/database/migrations/2026_11_18_120000_create_piaoju_seller_quota_snapshots.php new file mode 100644 index 00000000..717a038e --- /dev/null +++ b/database/migrations/2026_11_18_120000_create_piaoju_seller_quota_snapshots.php @@ -0,0 +1,51 @@ +hasTable(self::TABLE)) { + return; + } + + $schema->create(self::TABLE, function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('seller_key', 64)->unique('piaoju_seller_key_unique'); + $table->string('seller_name', 191); + $table->string('tax_number', 64)->nullable(); + $table->boolean('seller_status')->nullable(); + $table->string('auth_status', 32)->nullable(); + $table->string('auth_status_desc', 64)->nullable(); + $table->decimal('invoice_limit', 18, 2)->nullable(); + $table->dateTime('invoice_limit_updated_at')->nullable(); + $table->dateTime('source_fetched_at'); + $table->dateTime('synced_at'); + $table->timestamps(); + + $table->index('seller_name', 'piaoju_seller_name'); + $table->index('tax_number', 'piaoju_seller_tax_number'); + $table->index('invoice_limit_updated_at', 'piaoju_seller_limit_updated'); + }); + } + + public function down(): void + { + if (config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + Schema::connection((string) config('upstream_mirrors.connection', 'business_mirror')) + ->dropIfExists(self::TABLE); + } +}; diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index d70363f1..c90bafa9 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -16,6 +16,7 @@ | 状态 | 说明 | | --- | --- | +| 本次接入 | 票聚“销方管理”的 `可用发票额度(税局)`、`可用额度最新获取时间`、授权状态和纳税人识别号通过 `https://api.erp321.com/fp/fms/company/seller/page` 同步到 `piaoju_seller_quota_snapshots`;同步命令为 `piaoju:sync-invoice-quotas`,每 15 分钟执行一次,失败保留上一版。发票额度页按开票主体名称匹配票聚销方,不再用“本地开票额度 - 销项金额”冒充最新可用额度;未授权、授权过期、未匹配或票聚未返回值时显示明确状态。会话 Cookie 只放被 Git 忽略的 `runtime/private/piaoju-cookie.txt` 或服务器私有环境变量,不进入代码、日志和 PR。 | | 本次接入 | 顾家过账基础数据读取聚水潭“销售主题分析(新版)→ 商品利润 → 明细(订单商品)”10 月导出,仅保留天猫、京东、拼多多和抖音的 12 家 HX 旗舰店,写入 `kuka_posting_base_rows`;导入摘要写入 `kuka_posting_base_imports`。只保存前 40 个聚水潭原始字段,后续成本映射、报价和过账分类不混入基础数据。XLSX 通过 `business-mirror:import-kuka-posting-base` 流式读取,校验 12 家店铺均有数据后,在单一事务内整月替换;文件缺失、字段错误或中断时保留上一版。当前 2026 年 10 月导出为 13,949 行。 | | 本次接入 | `furniture3d_prod` PostgreSQL 只读库用于顾家发货明细映射:物料编号优先使用 `public.BarcodePrintImportRecord.updates.materialNo`,其次用 `public.SupplyChainProductArchive.sku` 对应聚水潭“货号”并校验候选 `barcode`,最后按 `updates.brandSkuCode` 对应报价单物料描述前缀回退;命中后必须存在报价单生效 `MaterialNumber`。同一物料编号允许多个货号共用,只要求单个货号内部候选唯一。页面“货号”先用聚水潭“款式编码”匹配 `BarcodePrintImportRecord.normalizedSku` 并取最新非空 `updates.brandSkuCode`;款式编码未命中时再用原始“货号”匹配同一张表;两级都未命中时保留聚水潭原货号。因此同一款式编码下的多个原始货号共享款式品牌货号,个别只有货号品牌映射的记录也能回退命中。物料编号和成本始终按聚水潭原始货号计算。款式和货号的品牌紧凑结果分别写入 `kuka_posting_brand_item_map_rows`、`kuka_posting_item_brand_item_map_rows`,物料映射写入 `kuka_posting_material_map_rows`;不复制整库、不在页面直连上游。每日 05:50 执行 `business-mirror:sync-kuka-posting-material-map`。 | | 本次接入 | 钉钉考勤 `attendance/list` 按财务中心在职成员同步到 `ding_attendance_records`,保留打卡记录 ID、用户、工作日期、上下班类型、打卡结果、审批标识、审批实例和打卡时间;每 15 分钟回看 35 天,按 7 天窗口和 50 人上限分页。钉钉排班通过 `getScheduleByRange` 同步到 `ding_attendance_schedule_records`,保留逐日排班 ID、用户、考勤组、班次、是否休息、变更状态和完整源数据;本机脚本为 `scripts/sync-ding-attendance-schedules.py`,导入命令为 `business-mirror:import-ding-attendance-schedules`,默认覆盖最近 95 天,查询不完整时拒绝覆盖旧镜像。日志漏写扣分只统计钉钉排班明确为工作日的日期,并继续排除没有日志但有“请假 / 休息 / 调休”等审批标记的日期;排班或考勤镜像未完成时扣分暂不计算,周五、周末或法定班次调整均以公司真实排班为准。依赖权限 `qyapi_attendance_isv_query_result`、`qyapi_get_attendance_data`。 | diff --git a/resources/views/business/pages/invoice_quota.blade.php b/resources/views/business/pages/invoice_quota.blade.php index b9906092..22270840 100644 --- a/resources/views/business/pages/invoice_quota.blade.php +++ b/resources/views/business/pages/invoice_quota.blade.php @@ -4,7 +4,6 @@ $sellerEntity = $sellerEntity ?? ''; $rows = $rows ?? collect(); $summary = $summary ?? []; - $warningRate = $warningRate ?? 80; $loadError = $loadError ?? null; @endphp @@ -51,36 +50,6 @@ color: var(--vip-danger, #b80000); } - .invoice-quota-usage { - display: flex; - min-width: 8.5rem; - align-items: center; - gap: 0.5rem; - } - - .invoice-quota-usage__track { - display: block; - width: 5rem; - height: 0.375rem; - overflow: hidden; - border-radius: 999px; - background: #ebe7df; - } - - .invoice-quota-usage__bar { - display: block; - height: 100%; - border-radius: inherit; - background: var(--vip-content-accent-dark, #856632); - } - - .invoice-quota-usage__value { - min-width: 3rem; - color: var(--vip-content-muted, #595959); - font-variant-numeric: tabular-nums; - text-align: right; - } - .invoice-quota-status { display: inline-flex; height: 1.5rem; @@ -203,22 +172,16 @@ 按当前筛选范围内的销项金额汇总
-
可用额度
-
(float) ($summary['remaining_total'] ?? 0) < 0])> - {{ number_format((float) ($summary['remaining_total'] ?? 0), 2) }} +
票聚可用额度
+
(float) ($summary['available_total'] ?? 0) < 0])> + {{ number_format((float) ($summary['available_total'] ?? 0), 2) }}
- - @if (($summary['usage_rate'] ?? null) !== null) - 整体使用率 {{ number_format((float) $summary['usage_rate'], 1) }}% - @else - 当前范围未设置开票额度 - @endif - + 已匹配 {{ (int) ($summary['matched_count'] ?? 0) }} 个主体
-
风险主体
-
{{ (int) ($summary['attention_count'] ?? 0) }}
- 超额 {{ (int) ($summary['exceeded_count'] ?? 0) }} · 需关注 {{ (int) ($summary['warning_count'] ?? 0) }} +
未匹配主体
+
{{ (int) ($summary['unmatched_count'] ?? 0) }}
+ 不可查看 {{ (int) ($summary['unavailable_count'] ?? 0) }} · 额度不足 {{ (int) ($summary['insufficient_count'] ?? 0) }}
@endunless @@ -234,8 +197,8 @@ 开票员 开票额度 已开票金额 - 可用额度 - 使用率 + 票聚可用额度 + 额度更新时间 状态 @@ -248,21 +211,14 @@ {{ $row->invoice_issuer ?: '—' }} {{ number_format((float) $row->invoice_limit, 2) }} {{ number_format((float) $row->output_amount, 2) }} - $row->remaining < 0])> - {{ number_format((float) $row->remaining, 2) }} - - - @if ($row->usage_rate !== null) -
- - {{ number_format((float) $row->usage_rate, 1) }}% -
+ $row->available_amount !== null && $row->available_amount < 0])> + @if ($row->available_amount !== null) + {{ number_format((float) $row->available_amount, 2) }} @else - — + — @endif + {{ $row->quota_updated_at ?: '—' }} @@ -285,7 +241,10 @@

- 可用额度 = 开票额度 - 已开票金额;使用率达到 {{ number_format((float) $warningRate, 0) }}% 标记“需关注”,超过开票额度标记“超额”。开票额度为 0 且有已开票金额时同样按超额处理。 + “票聚可用额度”读取票聚·销方管理“可用发票额度(税局)”及最新获取时间,按开票主体名称匹配;未授权、授权过期或票聚未返回额度的主体不显示推测值。 + @if (!empty($summary['latest_source_fetched_at'])) + 最近同步:{{ $summary['latest_source_fetched_at'] }}。 + @endif

@if ($rows->total() > 0) diff --git a/tests/Feature/Business/InvoiceQuotaPageTest.php b/tests/Feature/Business/InvoiceQuotaPageTest.php index cfeedbf8..992acac7 100644 --- a/tests/Feature/Business/InvoiceQuotaPageTest.php +++ b/tests/Feature/Business/InvoiceQuotaPageTest.php @@ -4,6 +4,9 @@ namespace Tests\Feature\Business; use App\Models\Auth\Permission; use App\Models\Business\InvoiceBasic; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Schema; use Tests\Feature\FeatureTestCase; class InvoiceQuotaPageTest extends FeatureTestCase @@ -16,11 +19,32 @@ class InvoiceQuotaPageTest extends FeatureTestCase Permission::where('name', 'read-admin-panel')->firstOrFail() ); + config(['upstream_mirrors.connection' => 'sqlite']); + Schema::dropIfExists('piaoju_seller_quota_snapshots'); + Schema::create('piaoju_seller_quota_snapshots', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('seller_key', 64)->unique(); + $table->string('seller_name', 191); + $table->string('tax_number', 64)->nullable(); + $table->boolean('seller_status')->nullable(); + $table->string('auth_status', 32)->nullable(); + $table->string('auth_status_desc', 64)->nullable(); + $table->decimal('invoice_limit', 18, 2)->nullable(); + $table->dateTime('invoice_limit_updated_at')->nullable(); + $table->dateTime('source_fetched_at'); + $table->dateTime('synced_at'); + $table->timestamps(); + }); + $this->createInvoiceBasic('甲公司', '甲店铺组', 10000, 8500, '2026-11'); $this->createInvoiceBasic('乙公司', '乙店铺', 2000, 2500, '2026-11'); $this->createInvoiceBasic('丙公司', '丙店铺', 5000, 1000, '2026-11'); $this->createInvoiceBasic('零额度公司', '零额度店铺', 0, 0, '2026-11'); $this->createInvoiceBasic('历史公司', '历史店铺', 100, 100, '2026-10'); + + $this->createPiaojuSnapshot('pi-1', '甲公司', 15000, '2026-11-18 13:30:07'); + $this->createPiaojuSnapshot('pi-2', '乙公司', -100, '2026-11-18 13:51:43'); + $this->createPiaojuSnapshot('pi-3', '丙公司', 4000, '2026-11-18 13:29:10'); } public function test_invoice_quota_is_listed_after_invoice_basic_information(): void @@ -34,7 +58,7 @@ class InvoiceQuotaPageTest extends FeatureTestCase ); } - public function test_invoice_quota_defaults_to_latest_period_and_shows_usage_summary(): void + public function test_invoice_quota_defaults_to_latest_period_and_shows_ticket_union_summary(): void { $this->loginAs() ->get($this->pageUrl()) @@ -43,17 +67,17 @@ class InvoiceQuotaPageTest extends FeatureTestCase ->assertSeeText('当前开票额度') ->assertSeeText('17,000.00') ->assertSeeText('12,000.00') - ->assertSeeText('5,000.00') + ->assertSeeText('18,900.00') ->assertSeeText('甲公司') + ->assertSeeText('15,000.00') ->assertSeeText('8,500.00') - ->assertSeeText('1,500.00') - ->assertSeeText('85.0%') + ->assertDontSeeText('1,500.00') ->assertSeeText('乙公司') - ->assertSeeText('-500.00') - ->assertSeeText('超额') - ->assertSeeText('需关注') - ->assertSeeText('未设置额度') - ->assertSeeText('超额 1 · 需关注 1') + ->assertSeeText('-100.00') + ->assertSeeText('额度不足') + ->assertSeeText('未匹配') + ->assertSeeText('不可查看 0 · 额度不足 1') + ->assertSeeText('2026-11-18 13:30') ->assertDontSeeText('历史公司') ->assertSee('