CaiWuXiTong/modules/EcommerceFinance/Repositories/DingInvoiceDataMirrorRepository.php

453 lines
17 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Repositories;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\DingInvoiceWorkbookImporter;
use RuntimeException;
class DingInvoiceDataMirrorRepository
{
public const PER_PAGE_OPTIONS = [50, 100, 200];
public const VIEW_DETAIL = 'detail';
public const VIEW_FLOWS = 'flows';
public const INVOICE_STATES = [
'all' => '全部状态',
'has_invoice' => '有发票',
'no_invoice' => '无票',
'needs_review' => '待复核',
];
private ConnectionInterface $connection;
public function __construct(DatabaseManager $database)
{
$this->connection = $database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
public function scope(): string
{
return trim((string) config(
'upstream_mirrors.ding_process_details.scope',
'personal_permission',
)) ?: 'personal_permission';
}
public function ready(): bool
{
$schema = Schema::connection($this->connection->getName());
if (! $schema->hasTable('ding_invoice_flow_mirror')
|| ! $schema->hasTable('ding_invoice_record_mirror')) {
return false;
}
$state = $this->state();
if ($state !== null && ($state['initial_completed_at'] ?? null) !== null) {
return true;
}
return (int) $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $this->scope())
->count() > 0;
}
/** @return array<string,mixed>|null */
public function state(): ?array
{
if (! Schema::connection($this->connection->getName())
->hasTable('business_mirror_table_states')) {
return null;
}
$row = $this->connection->table('business_mirror_table_states')
->where('dataset_key', DingInvoiceWorkbookImporter::DATASET_KEY)
->first();
return $row === null ? null : (array) $row;
}
/** @return list<string> */
public function months(): array
{
if (! $this->ready()) {
return [];
}
return $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $this->scope())
->whereNotNull('paid_month')
->where('paid_month', '!=', '')
->distinct()
->orderByDesc('paid_month')
->pluck('paid_month')
->map(static fn (mixed $value): string => (string) $value)
->values()
->all();
}
/**
* @param array<string,mixed> $filters
* @return array{data:list<object>,total:int,summary:array<string,mixed>,state:?array}
*/
public function paginate(array $filters, int $page, int $perPage): array
{
if (! $this->ready()) {
throw new RuntimeException('ding_invoice_mirror_not_ready');
}
$page = max(1, $page);
$perPage = in_array($perPage, self::PER_PAGE_OPTIONS, true) ? $perPage : 50;
$query = $filters['view'] === self::VIEW_FLOWS
? $this->flowQuery($filters)
: $this->detailQuery($filters);
$total = (clone $query)->count();
$data = $query
->forPage($page, $perPage)
->get()
->all();
return [
'data' => $data,
'total' => $total,
'summary' => $this->summary($filters),
'state' => $this->state(),
];
}
/** @param array<string,mixed> $filters */
public function filterOptions(array $filters): array
{
if (! $this->ready()) {
return ['invoice_types' => []];
}
$query = $this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $this->scope());
if (($filters['month'] ?? '') !== '') {
$query->where('paid_month', $filters['month']);
}
return [
'invoice_types' => $query
->whereNotNull('invoice_type')
->where('invoice_type', '!=', '')
->distinct()
->orderBy('invoice_type')
->pluck('invoice_type')
->map(static fn (mixed $value): string => (string) $value)
->values()
->all(),
];
}
/** @param array<string,mixed> $filters */
public function exportRows(array $filters): iterable
{
if (! $this->ready()) {
throw new RuntimeException('ding_invoice_mirror_not_ready');
}
$query = $filters['view'] === self::VIEW_FLOWS
? $this->flowQuery($filters)
: $this->detailQuery($filters);
foreach ($query->cursor() as $row) {
yield (array) $row;
}
}
/** @param array<string,mixed> $filters */
private function flowQuery(array $filters): Builder
{
$query = $this->connection->table('ding_invoice_flow_mirror as f')
->select([
'f.id',
'f.business_id',
'f.process_instance_id',
'f.paid_month',
'f.title',
'f.originator_name',
'f.document_type',
'f.expense_type',
'f.payee_name',
'f.paid_at',
'f.payment_amount',
'f.payment_total',
'f.invoice_count',
'f.invoice_total',
'f.scan_status',
'f.attachment_count',
'f.scanned_file_count',
'f.last_error',
'f.source_name',
'f.scanned_at',
])
->where('f.source_scope', $this->scope());
$this->applyFlowFilters($query, $filters);
return $query
->orderByDesc('f.paid_at')
->orderByDesc('f.business_id');
}
/** @param array<string,mixed> $filters */
private function detailQuery(array $filters): Builder
{
$query = $this->connection->table('ding_invoice_record_mirror as r')
->join('ding_invoice_flow_mirror as f', function ($join): void {
$join->on('f.business_id', '=', 'r.business_id')
->on('f.source_scope', '=', 'r.source_scope');
})
->select([
'r.id',
'r.business_id',
'r.process_instance_id',
'r.paid_month',
'r.invoice_type',
'r.seller_name',
'r.seller_tax_no',
'r.buyer_name',
'r.buyer_tax_no',
'r.invoice_total',
'r.invoice_number',
'r.invoice_date',
'r.item_name',
'r.amount_without_tax',
'r.tax_rate',
'r.tax_amount',
'r.source_file_id',
'r.source_file_name',
'r.source_file_type',
'r.source_field',
'r.ocr_provider',
'f.title',
'f.originator_name',
'f.document_type',
'f.expense_type',
'f.payee_name',
'f.paid_at',
'f.payment_amount',
'f.payment_total',
'f.invoice_count',
'f.invoice_total as flow_invoice_total',
'f.scan_status',
'f.last_error',
])
->where('r.source_scope', $this->scope());
$this->applyFlowFilters($query, $filters, 'f');
if (($filters['invoice_type'] ?? '') !== '') {
$query->where('r.invoice_type', $filters['invoice_type']);
}
if (($filters['keyword'] ?? '') !== '') {
$keyword = '%' . $filters['keyword'] . '%';
$query->where(function (Builder $nested) use ($keyword, $filters): void {
foreach ([
'r.business_id',
'r.invoice_number',
'r.seller_name',
'r.seller_tax_no',
'r.buyer_name',
'r.buyer_tax_no',
'r.item_name',
'f.title',
'f.originator_name',
'f.payee_name',
] as $column) {
$nested->orWhere($column, 'like', $keyword);
}
});
}
return $query
->orderByDesc('f.paid_at')
->orderByDesc('f.business_id')
->orderBy('r.id');
}
/** @param array<string,mixed> $filters */
private function applyFlowFilters(Builder $query, array $filters, string $alias = 'f'): void
{
$query->where("{$alias}.source_scope", $this->scope());
if (($filters['month'] ?? '') !== '') {
$query->where("{$alias}.paid_month", $filters['month']);
}
match ($filters['invoice_state'] ?? 'all') {
'has_invoice' => $query->where("{$alias}.invoice_count", '>', 0),
'no_invoice' => $query
->where("{$alias}.invoice_count", '=', 0)
->where(function (Builder $nested) use ($alias): void {
$nested->whereNull("{$alias}.last_error")
->orWhere("{$alias}.last_error", '=', '');
}),
'needs_review' => $query
->where(function (Builder $nested) use ($alias): void {
$nested->whereIn("{$alias}.scan_status", ['partial', 'failed'])
->orWhere(function (Builder $failed) use ($alias): void {
$failed->whereNotNull("{$alias}.last_error")
->where("{$alias}.last_error", '!=', '');
});
}),
default => null,
};
if (($filters['invoice_type'] ?? '') !== ''
&& $filters['view'] === self::VIEW_FLOWS) {
$query->whereExists(function (Builder $exists) use ($filters): void {
$exists->selectRaw('1')
->from('ding_invoice_record_mirror as ri')
->whereColumn('ri.source_scope', 'f.source_scope')
->whereColumn('ri.business_id', 'f.business_id')
->where('ri.invoice_type', $filters['invoice_type']);
});
}
if (($filters['keyword'] ?? '') !== ''
&& $filters['view'] === self::VIEW_FLOWS) {
$keyword = '%' . $filters['keyword'] . '%';
$query->where(function (Builder $nested) use ($keyword, $alias, $filters): void {
foreach ([
"{$alias}.business_id",
"{$alias}.title",
"{$alias}.originator_name",
"{$alias}.document_type",
"{$alias}.expense_type",
"{$alias}.payee_name",
] as $column) {
$nested->orWhere($column, 'like', $keyword);
}
if ($filters['view'] === self::VIEW_FLOWS) {
$nested->orWhereExists(function (Builder $exists) use ($keyword): void {
$exists->selectRaw('1')
->from('ding_invoice_record_mirror as rk')
->whereColumn('rk.source_scope', 'f.source_scope')
->whereColumn('rk.business_id', 'f.business_id')
->where(function (Builder $invoiceSearch) use ($keyword): void {
foreach (['invoice_number', 'seller_name', 'buyer_name', 'item_name'] as $column) {
$invoiceSearch->orWhere("rk.{$column}", 'like', $keyword);
}
});
});
}
});
}
}
/** @param array<string,mixed> $filters */
private function summary(array $filters): array
{
$query = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $this->scope());
if (($filters['month'] ?? '') !== '') {
$query->where('paid_month', $filters['month']);
}
if (($filters['invoice_state'] ?? 'all') === 'has_invoice') {
$query->where('invoice_count', '>', 0);
} elseif (($filters['invoice_state'] ?? 'all') === 'no_invoice') {
$query->where('invoice_count', 0)
->where(function (Builder $nested): void {
$nested->whereNull('last_error')->orWhere('last_error', '');
});
} elseif (($filters['invoice_state'] ?? 'all') === 'needs_review') {
$query->where(function (Builder $nested): void {
$nested->whereIn('scan_status', ['partial', 'failed'])
->orWhere(function (Builder $failed): void {
$failed->whereNotNull('last_error')->where('last_error', '!=', '');
});
});
}
if (($filters['invoice_type'] ?? '') !== '') {
$query->whereExists(function (Builder $exists) use ($filters): void {
$exists->selectRaw('1')
->from('ding_invoice_record_mirror as summary_invoice')
->whereColumn('summary_invoice.source_scope', 'ding_invoice_flow_mirror.source_scope')
->whereColumn('summary_invoice.business_id', 'ding_invoice_flow_mirror.business_id')
->where('summary_invoice.invoice_type', $filters['invoice_type']);
});
}
if (($filters['keyword'] ?? '') !== '') {
$keyword = '%' . $filters['keyword'] . '%';
$query->where(function (Builder $nested) use ($keyword, $filters): void {
foreach ([
'business_id',
'title',
'originator_name',
'document_type',
'expense_type',
'payee_name',
] as $column) {
$nested->orWhere($column, 'like', $keyword);
}
if (($filters['view'] ?? self::VIEW_DETAIL) === self::VIEW_DETAIL) {
$nested->orWhereExists(function (Builder $exists) use ($keyword): void {
$exists->selectRaw('1')
->from('ding_invoice_record_mirror as summary_invoice_search')
->whereColumn(
'summary_invoice_search.source_scope',
'ding_invoice_flow_mirror.source_scope',
)
->whereColumn(
'summary_invoice_search.business_id',
'ding_invoice_flow_mirror.business_id',
)
->where(function (Builder $invoiceSearch) use ($keyword): void {
foreach ([
'invoice_number',
'seller_name',
'seller_tax_no',
'buyer_name',
'buyer_tax_no',
'item_name',
] as $column) {
$invoiceSearch->orWhere(
'summary_invoice_search.' . $column,
'like',
$keyword,
);
}
});
});
}
});
}
$rows = (clone $query)->get([
'payment_amount',
'invoice_count',
'invoice_total',
'scan_status',
'last_error',
]);
$payment = round((float) $rows->sum('payment_amount'), 2);
$invoice = round((float) $rows->sum('invoice_total'), 2);
return [
'flows' => $rows->count(),
'payment_amount' => $payment,
'invoice_count' => (int) $rows->sum('invoice_count'),
'invoice_total' => $invoice,
'no_invoice_flows' => $rows->filter(
static fn (object $row): bool => (int) $row->invoice_count === 0
&& ($row->last_error === null || $row->last_error === ''),
)->count(),
'needs_review_flows' => $rows->filter(
static fn (object $row): bool => in_array((string) $row->scan_status, ['partial', 'failed'], true)
|| ($row->last_error !== null && $row->last_error !== ''),
)->count(),
'invoice_rate' => $payment > 0 ? $invoice / $payment : 0,
];
}
}