feat: 发票额度读取票聚销方可用额度 #1233
@ -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' => '发票额度数据暂时无法读取,请稍后重试。',
|
||||
];
|
||||
}
|
||||
|
||||
170
app/Business/Piaoju/PiaojuSellerQuotaClient.php
Normal file
170
app/Business/Piaoju/PiaojuSellerQuotaClient.php
Normal file
@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\Piaoju;
|
||||
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use RuntimeException;
|
||||
|
||||
class PiaojuSellerQuotaClient
|
||||
{
|
||||
/**
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
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<array<string,mixed>>,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<array<string,mixed>>,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;
|
||||
}
|
||||
}
|
||||
128
app/Business/Piaoju/PiaojuSellerQuotaImporter.php
Normal file
128
app/Business/Piaoju/PiaojuSellerQuotaImporter.php
Normal file
@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\Piaoju;
|
||||
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class PiaojuSellerQuotaImporter
|
||||
{
|
||||
public const TABLE = 'piaoju_seller_quota_snapshots';
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $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<array<string,mixed>> $rows
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
57
app/Business/Piaoju/PiaojuSellerQuotaRepository.php
Normal file
57
app/Business/Piaoju/PiaojuSellerQuotaRepository.php
Normal file
@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\Piaoju;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Throwable;
|
||||
|
||||
class PiaojuSellerQuotaRepository
|
||||
{
|
||||
/**
|
||||
* @return Collection<string,object>
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
81
app/Console/Commands/SyncPiaojuSellerQuotas.php
Normal file
81
app/Console/Commands/SyncPiaojuSellerQuotas.php
Normal file
@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Business\Piaoju\PiaojuSellerQuotaClient;
|
||||
use App\Business\Piaoju\PiaojuSellerQuotaImporter;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
class SyncPiaojuSellerQuotas extends Command
|
||||
{
|
||||
protected $signature = 'piaoju:sync-invoice-quotas
|
||||
{--file= : 票聚销方列表 JSON 文件;省略时调用票聚接口}
|
||||
{--stdin : 从标准输入读取票聚销方列表 JSON}
|
||||
{--dry-run : 只读取并校验票聚响应,不写共享镜像}';
|
||||
|
||||
protected $description = '同步票聚销方管理的最新可用发票额度到共享业务镜像';
|
||||
|
||||
public function handle(PiaojuSellerQuotaClient $client, PiaojuSellerQuotaImporter $importer): int
|
||||
{
|
||||
try {
|
||||
$rows = $this->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<array<string,mixed>>
|
||||
*/
|
||||
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'));
|
||||
}
|
||||
}
|
||||
@ -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 * * * *')
|
||||
|
||||
@ -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',
|
||||
|
||||
13
config/piaoju.php
Normal file
13
config/piaoju.php
Normal file
@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'api_base_url' => 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,
|
||||
];
|
||||
@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public const TABLE = 'piaoju_seller_quota_snapshots';
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
if (config('system_database.mode', 'bootstrap') === 'bootstrap') {
|
||||
return;
|
||||
}
|
||||
|
||||
$schema = Schema::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
|
||||
if ($schema->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);
|
||||
}
|
||||
};
|
||||
@ -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`。 |
|
||||
|
||||
@ -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 @@
|
||||
<small>按当前筛选范围内的销项金额汇总</small>
|
||||
</div>
|
||||
<div>
|
||||
<dt>可用额度</dt>
|
||||
<dd @class(['is-negative' => (float) ($summary['remaining_total'] ?? 0) < 0])>
|
||||
{{ number_format((float) ($summary['remaining_total'] ?? 0), 2) }}
|
||||
<dt>票聚可用额度</dt>
|
||||
<dd @class(['is-negative' => (float) ($summary['available_total'] ?? 0) < 0])>
|
||||
{{ number_format((float) ($summary['available_total'] ?? 0), 2) }}
|
||||
</dd>
|
||||
<small>
|
||||
@if (($summary['usage_rate'] ?? null) !== null)
|
||||
整体使用率 {{ number_format((float) $summary['usage_rate'], 1) }}%
|
||||
@else
|
||||
当前范围未设置开票额度
|
||||
@endif
|
||||
</small>
|
||||
<small>已匹配 {{ (int) ($summary['matched_count'] ?? 0) }} 个主体</small>
|
||||
</div>
|
||||
<div>
|
||||
<dt>风险主体</dt>
|
||||
<dd>{{ (int) ($summary['attention_count'] ?? 0) }}</dd>
|
||||
<small>超额 {{ (int) ($summary['exceeded_count'] ?? 0) }} · 需关注 {{ (int) ($summary['warning_count'] ?? 0) }}</small>
|
||||
<dt>未匹配主体</dt>
|
||||
<dd>{{ (int) ($summary['unmatched_count'] ?? 0) }}</dd>
|
||||
<small>不可查看 {{ (int) ($summary['unavailable_count'] ?? 0) }} · 额度不足 {{ (int) ($summary['insufficient_count'] ?? 0) }}</small>
|
||||
</div>
|
||||
</dl>
|
||||
@endunless
|
||||
@ -234,8 +197,8 @@
|
||||
<th>开票员</th>
|
||||
<th class="is-number">开票额度</th>
|
||||
<th class="is-number">已开票金额</th>
|
||||
<th class="is-number">可用额度</th>
|
||||
<th>使用率</th>
|
||||
<th class="is-number">票聚可用额度</th>
|
||||
<th>额度更新时间</th>
|
||||
<th>状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@ -248,21 +211,14 @@
|
||||
<td>{{ $row->invoice_issuer ?: '—' }}</td>
|
||||
<td class="is-number">{{ number_format((float) $row->invoice_limit, 2) }}</td>
|
||||
<td class="is-number">{{ number_format((float) $row->output_amount, 2) }}</td>
|
||||
<td @class(['is-number', 'is-negative' => $row->remaining < 0])>
|
||||
{{ number_format((float) $row->remaining, 2) }}
|
||||
</td>
|
||||
<td>
|
||||
@if ($row->usage_rate !== null)
|
||||
<div class="invoice-quota-usage" title="已开票金额 ÷ 开票额度">
|
||||
<span class="invoice-quota-usage__track" aria-hidden="true">
|
||||
<span class="invoice-quota-usage__bar" style="width: {{ $row->usage_bar_width }}%"></span>
|
||||
</span>
|
||||
<span class="invoice-quota-usage__value">{{ number_format((float) $row->usage_rate, 1) }}%</span>
|
||||
</div>
|
||||
<td @class(['is-number', 'is-negative' => $row->available_amount !== null && $row->available_amount < 0])>
|
||||
@if ($row->available_amount !== null)
|
||||
{{ number_format((float) $row->available_amount, 2) }}
|
||||
@else
|
||||
<span class="invoice-quota-usage__value">—</span>
|
||||
—
|
||||
@endif
|
||||
</td>
|
||||
<td>{{ $row->quota_updated_at ?: '—' }}</td>
|
||||
<td>
|
||||
<span class="invoice-quota-status is-{{ $row->status_tone }}">
|
||||
<span class="material-icons-outlined" aria-hidden="true">{{ $row->status_icon }}</span>
|
||||
@ -285,7 +241,10 @@
|
||||
</table>
|
||||
</div>
|
||||
<p class="invoice-quota-note">
|
||||
可用额度 = 开票额度 - 已开票金额;使用率达到 {{ number_format((float) $warningRate, 0) }}% 标记“需关注”,超过开票额度标记“超额”。开票额度为 0 且有已开票金额时同样按超额处理。
|
||||
“票聚可用额度”读取票聚·销方管理“可用发票额度(税局)”及最新获取时间,按开票主体名称匹配;未授权、授权过期或票聚未返回额度的主体不显示推测值。
|
||||
@if (!empty($summary['latest_source_fetched_at']))
|
||||
最近同步:{{ $summary['latest_source_fetched_at'] }}。
|
||||
@endif
|
||||
</p>
|
||||
|
||||
@if ($rows->total() > 0)
|
||||
|
||||
@ -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('<option value="2026-11" selected>', false);
|
||||
}
|
||||
@ -65,6 +89,7 @@ class InvoiceQuotaPageTest extends FeatureTestCase
|
||||
->assertOk()
|
||||
->assertSeeText('甲公司')
|
||||
->assertSeeText('10,000.00')
|
||||
->assertSeeText('15,000.00')
|
||||
->assertSeeText('8,500.00')
|
||||
->assertDontSeeText('乙公司')
|
||||
->assertDontSeeText('丙公司');
|
||||
@ -77,6 +102,28 @@ class InvoiceQuotaPageTest extends FeatureTestCase
|
||||
->assertSee('<option value="2026-10" selected>', false);
|
||||
}
|
||||
|
||||
private function createPiaojuSnapshot(
|
||||
string $sellerKey,
|
||||
string $sellerName,
|
||||
float $invoiceLimit,
|
||||
string $updatedAt
|
||||
): void {
|
||||
DB::connection('sqlite')->table('piaoju_seller_quota_snapshots')->insert([
|
||||
'seller_key' => $sellerKey,
|
||||
'seller_name' => $sellerName,
|
||||
'tax_number' => 'TAX-' . $sellerKey,
|
||||
'seller_status' => true,
|
||||
'auth_status' => 'AUTHENTICATED',
|
||||
'auth_status_desc' => '已授权',
|
||||
'invoice_limit' => $invoiceLimit,
|
||||
'invoice_limit_updated_at' => $updatedAt,
|
||||
'source_fetched_at' => '2026-11-18 14:00:00',
|
||||
'synced_at' => '2026-11-18 14:00:01',
|
||||
'created_at' => '2026-11-18 14:00:01',
|
||||
'updated_at' => '2026-11-18 14:00:01',
|
||||
]);
|
||||
}
|
||||
|
||||
private function createInvoiceBasic(
|
||||
string $entity,
|
||||
string $storeName,
|
||||
|
||||
115
tests/Feature/Business/PiaojuSellerQuotaSyncTest.php
Normal file
115
tests/Feature/Business/PiaojuSellerQuotaSyncTest.php
Normal file
@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class PiaojuSellerQuotaSyncTest extends FeatureTestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
config([
|
||||
'upstream_mirrors.connection' => 'sqlite',
|
||||
'piaoju.cookie' => 'isLogin=1; u_sso_token=test-session',
|
||||
'piaoju.api_base_url' => 'https://api.erp321.com',
|
||||
]);
|
||||
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
public function test_it_replaces_the_shared_mirror_with_ticket_union_seller_quotas(): void
|
||||
{
|
||||
Http::fake([
|
||||
'https://api.erp321.com/fp/fms/company/seller/page' => Http::response([
|
||||
'code' => '0000',
|
||||
'data' => [
|
||||
[
|
||||
'id' => 101,
|
||||
'sellerName' => '甲公司',
|
||||
'taxNumber' => '91320000TEST000001',
|
||||
'status' => true,
|
||||
'authStatus' => 'AUTHENTICATED',
|
||||
'authStatusDesc' => '已授权',
|
||||
'invoiceLimit' => 128963.91,
|
||||
'invoiceLimitUpdated' => '2026-11-18 13:30:07',
|
||||
],
|
||||
[
|
||||
'id' => 102,
|
||||
'sellerName' => '乙公司',
|
||||
'taxNumber' => '91320000TEST000002',
|
||||
'status' => true,
|
||||
'authStatus' => 'AUTHENTICATED',
|
||||
'authStatusDesc' => '已授权',
|
||||
'invoiceLimit' => -100,
|
||||
'invoiceLimitUpdated' => '2026-11-18 13:51:43',
|
||||
],
|
||||
],
|
||||
'total' => 2,
|
||||
]),
|
||||
]);
|
||||
|
||||
$this->artisan('piaoju:sync-invoice-quotas')
|
||||
->expectsOutput('票聚销方额度同步完成:2 条。')
|
||||
->assertSuccessful();
|
||||
|
||||
$this->assertDatabaseHas('piaoju_seller_quota_snapshots', [
|
||||
'seller_key' => '91320000TEST000001',
|
||||
'seller_name' => '甲公司',
|
||||
'invoice_limit' => 128963.91,
|
||||
], 'sqlite');
|
||||
$this->assertDatabaseHas('piaoju_seller_quota_snapshots', [
|
||||
'seller_key' => '91320000TEST000002',
|
||||
'seller_name' => '乙公司',
|
||||
'invoice_limit' => -100,
|
||||
], 'sqlite');
|
||||
}
|
||||
|
||||
public function test_failed_sync_keeps_the_previous_mirror(): void
|
||||
{
|
||||
DB::connection('sqlite')->table('piaoju_seller_quota_snapshots')->insert([
|
||||
'seller_key' => 'old-1',
|
||||
'seller_name' => '旧主体',
|
||||
'invoice_limit' => 500,
|
||||
'source_fetched_at' => '2026-11-18 13:00:00',
|
||||
'synced_at' => '2026-11-18 13:00:01',
|
||||
'created_at' => '2026-11-18 13:00:01',
|
||||
'updated_at' => '2026-11-18 13:00:01',
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'https://api.erp321.com/fp/fms/company/seller/page' => Http::response([
|
||||
'code' => -1,
|
||||
'msg' => '未登录',
|
||||
]),
|
||||
]);
|
||||
|
||||
$this->artisan('piaoju:sync-invoice-quotas')
|
||||
->expectsOutput('票聚销方额度同步失败,已保留上一版镜像。')
|
||||
->assertFailed();
|
||||
|
||||
$this->assertDatabaseHas('piaoju_seller_quota_snapshots', [
|
||||
'seller_key' => 'old-1',
|
||||
'seller_name' => '旧主体',
|
||||
], 'sqlite');
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user