feat: 心选按索菲亚收票倒推收入和全额开票

心选人工填写索菲亚收票,按成本/90%倒推收入,内部开票按全额收入并继续向标签2顺延。
This commit is contained in:
DoDo 2026-11-09 15:01:50 +08:00
parent 27d0f6d9fe
commit 6334fa0adf
8 changed files with 426 additions and 44 deletions

View File

@ -16,14 +16,54 @@ class InternalFlowReportActions
InternalFlowReportRepository $repository,
InternalFlowProjection $projection,
int $record,
): JsonResponse|RedirectResponse {
return $this->updateReceipt(
$request,
$repository,
$projection,
$record,
'receipt_from_supplier',
'收票-供应商已保存。',
);
}
public function updateSuofeiyaReceipt(
Request $request,
InternalFlowReportRepository $repository,
InternalFlowProjection $projection,
int $record,
): JsonResponse|RedirectResponse {
$companyName = $repository->companyNameForRecord($record);
abort_if($companyName === null, 404);
$rule = config('internal_flow_report.cost_to_income.' . $companyName);
abort_unless(
is_array($rule) && ($rule['receipt_field'] ?? null) === 'receipt_from_suofeiya',
403,
);
return $this->updateReceipt(
$request,
$repository,
$projection,
$record,
'receipt_from_suofeiya',
'收票-索菲亚已保存,并已按 90% 成本率倒推收入。',
);
}
private function updateReceipt(
Request $request,
InternalFlowReportRepository $repository,
InternalFlowProjection $projection,
int $record,
string $field,
string $successMessage,
): JsonResponse|RedirectResponse {
$data = $request->validate([
'receipt_from_supplier' => ['present', 'nullable', 'numeric', 'min:0', 'max:99999999999999'],
$field => ['present', 'nullable', 'numeric', 'min:0', 'max:99999999999999'],
]);
$amount = $data['receipt_from_supplier'] === null
? null
: round((float) $data['receipt_from_supplier'], 2);
$companyName = $repository->updateSupplierReceipt($record, $amount, user_id());
$amount = $data[$field] === null ? null : round((float) $data[$field], 2);
$companyName = $repository->updateReceiptOverride($record, $field, $amount, user_id());
abort_if($companyName === null, 404);
$projectionPayload = null;
@ -32,7 +72,7 @@ class InternalFlowReportActions
$projectionPayload = $projection->forMonth();
} catch (Throwable $exception) {
report($exception);
$projectionError = '主体维度报表上月业绩暂时无法读取,已保存供应商收票,其他自动计算暂时保留原值。';
$projectionError = '主体维度报表上月业绩暂时无法读取,已保存人工收票,其他自动计算暂时保留原值。';
}
$filters = [
@ -48,12 +88,18 @@ class InternalFlowReportActions
'ok' => true,
'record' => [
'id' => (int) ($saved['id'] ?? $record),
'receipt_from_supplier' => $saved['receipt_from_supplier'] ?? null,
'receipt_field' => $field,
'receipt_amount' => $saved[$field] ?? null,
'projected_sales' => $saved['projected_sales'] ?? null,
'receipt_total' => $saved['receipt_total'] ?? null,
'remaining_gap' => $saved['remaining_gap'] ?? null,
],
'rows' => $rows->map(static fn (array $row): array => [
'id' => (int) $row['id'],
'projected_sales' => $row['projected_sales'] ?? null,
'invoiced_to_buyer' => $row['invoiced_to_buyer'] ?? null,
'internal_invoiced' => $row['internal_invoiced'] ?? null,
'required_input_cost' => $row['required_input_cost'] ?? null,
'internal_transfer_1' => $row['internal_transfer_1'] ?? null,
'internal_transfer_2' => $row['internal_transfer_2'] ?? null,
'internal_transfer_3' => $row['internal_transfer_3'] ?? null,
@ -67,7 +113,7 @@ class InternalFlowReportActions
return back()->with(
$projectionError === null ? 'success' : 'warning',
$projectionError ?? '收票-供应商已保存。',
$projectionError ?? $successMessage,
);
}
}

View File

@ -0,0 +1,15 @@
<?php
return [
/*
* 这些公司以指定收票金额倒推收入:成本金额 ÷ cost_to_income_rate。
* receipt_field 只在对应公司行显示为可填写。
*/
'cost_to_income' => [
'常州心选供应链有限公司' => [
'receipt_field' => 'receipt_from_suofeiya',
'cost_to_income_rate' => 0.90,
'internal_invoice_rate' => 1.00,
],
],
];

View File

@ -0,0 +1,39 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
$schema = Schema::connection($this->connection());
$table = 'business_internal_flow_supplier_receipt_overrides';
if (! $schema->hasTable($table) || $schema->hasColumn($table, 'receipt_from_suofeiya')) {
return;
}
$schema->table($table, function (Blueprint $blueprint): void {
$blueprint->decimal('receipt_from_suofeiya', 20, 6)->nullable()->after('receipt_from_supplier');
});
}
public function down(): void
{
$schema = Schema::connection($this->connection());
$table = 'business_internal_flow_supplier_receipt_overrides';
if ($schema->hasTable($table) && $schema->hasColumn($table, 'receipt_from_suofeiya')) {
$schema->table($table, function (Blueprint $blueprint): void {
$blueprint->dropColumn('receipt_from_suofeiya');
});
}
}
};

View File

@ -44,6 +44,11 @@ class InternalFlowReportRepository
'internal_transfer_3',
];
private const OVERRIDE_FIELDS = [
'receipt_from_supplier',
'receipt_from_suofeiya',
];
private readonly ConnectionInterface $connection;
public function __construct(
@ -130,12 +135,43 @@ class InternalFlowReportRepository
}
public function updateSupplierReceipt(int $id, ?float $amount, ?int $userId): ?string
{
return $this->updateReceiptOverride($id, 'receipt_from_supplier', $amount, $userId);
}
public function updateSuofeiyaReceipt(int $id, ?float $amount, ?int $userId): ?string
{
return $this->updateReceiptOverride($id, 'receipt_from_suofeiya', $amount, $userId);
}
public function companyNameForRecord(int $id): ?string
{
if (! $this->ready()) {
return null;
}
$companyName = $this->connection->table(self::TABLE)->where('id', $id)->value('company_name');
return $companyName === null ? null : trim((string) $companyName);
}
public function updateReceiptOverride(int $id, string $field, ?float $amount, ?int $userId): ?string
{
if (! $this->ready() || ! $this->supplierReceiptOverridesReady()) {
throw new RuntimeException('内部流转供应商收票保存表尚未就绪。');
}
if (! in_array($field, self::OVERRIDE_FIELDS, true)) {
throw new RuntimeException('不支持的人工收票字段。');
}
if ($field === 'receipt_from_suofeiya'
&& ! $this->connection->getSchemaBuilder()->hasColumn(
self::SUPPLIER_RECEIPT_OVERRIDES_TABLE,
'receipt_from_suofeiya',
)) {
throw new RuntimeException('索菲亚收票保存字段尚未就绪,请先完成数据库迁移。');
}
return $this->connection->transaction(function () use ($id, $amount, $userId): ?string {
return $this->connection->transaction(function () use ($id, $field, $amount, $userId): ?string {
$record = $this->connection->table(self::TABLE)
->where('id', $id)
->lockForUpdate()
@ -147,7 +183,7 @@ class InternalFlowReportRepository
$companyName = trim((string) ($record->company_name ?? ''));
$now = now();
$values = [
'receipt_from_supplier' => $amount === null
$field => $amount === null
? null
: number_format($amount, 6, '.', ''),
'updated_by' => $userId,
@ -213,18 +249,56 @@ class InternalFlowReportRepository
$salesByCompany = is_array($projection['sales_by_company'] ?? null)
? $projection['sales_by_company']
: null;
$costToIncomeRules = (array) config('internal_flow_report.cost_to_income', []);
$rows = array_map(function (array $row) use ($overrides, $projection, $salesByCompany): array {
$rows = array_map(function (array $row) use (
$overrides,
$projection,
$salesByCompany,
$costToIncomeRules,
): array {
$companyName = trim((string) ($row['company_name'] ?? ''));
if (array_key_exists($companyName, $overrides)) {
$row['receipt_from_supplier'] = $overrides[$companyName];
$companyOverrides = $overrides[$companyName] ?? [];
foreach (self::OVERRIDE_FIELDS as $field) {
if (array_key_exists($field, $companyOverrides)) {
$row[$field] = $companyOverrides[$field];
}
}
foreach (self::RECEIPT_FIELDS as $field) {
$row[$field] = $this->nullableAmount($row[$field] ?? null);
}
if ($projection !== null && $salesByCompany !== null) {
$costToIncome = $costToIncomeRules[$companyName] ?? null;
$manualReceiptField = is_array($costToIncome)
? (string) ($costToIncome['receipt_field'] ?? '')
: '';
$manualCost = null;
if ($manualReceiptField !== ''
&& array_key_exists($manualReceiptField, $companyOverrides)
&& $companyOverrides[$manualReceiptField] !== null) {
$manualCost = $this->nullableAmount($companyOverrides[$manualReceiptField]);
}
$costToIncomeRate = is_array($costToIncome)
? max(0.000001, (float) ($costToIncome['cost_to_income_rate'] ?? 0.9))
: 0.9;
$internalInvoiceRate = is_array($costToIncome)
? max(0.0, (float) ($costToIncome['internal_invoice_rate'] ?? InternalFlowProjection::INTERNAL_INVOICE_RATE))
: InternalFlowProjection::INTERNAL_INVOICE_RATE;
if ($manualCost !== null) {
$projectedSales = round($manualCost / $costToIncomeRate, 6);
$row['projected_sales'] = $projectedSales;
$row['invoiced_to_buyer'] = round(
$projectedSales * InternalFlowProjection::BUYER_INVOICE_RATE,
6,
);
$row['internal_invoiced'] = round(
$projectedSales * $internalInvoiceRate,
6,
);
$row['required_input_cost'] = round($manualCost, 6);
} elseif ($projection !== null && $salesByCompany !== null) {
$projectedSales = array_key_exists($companyName, $salesByCompany)
? $this->nullableAmount($salesByCompany[$companyName])
: null;
@ -347,7 +421,7 @@ class InternalFlowReportRepository
/**
* @param list<string> $companyNames
* @return array<string,float|null>
* @return array<string,array<string,float|null>>
*/
private function receiptOverrides(array $companyNames): array
{
@ -359,13 +433,26 @@ class InternalFlowReportRepository
static fn (mixed $name): string => trim((string) $name),
$companyNames,
))));
$columns = ['company_name', 'receipt_from_supplier'];
if ($this->connection->getSchemaBuilder()->hasColumn(
self::SUPPLIER_RECEIPT_OVERRIDES_TABLE,
'receipt_from_suofeiya',
)) {
$columns[] = 'receipt_from_suofeiya';
}
$overrides = [];
foreach (array_chunk($companyNames, 500) as $chunk) {
$rows = $this->connection->table(self::SUPPLIER_RECEIPT_OVERRIDES_TABLE)
->whereIn('company_name', $chunk)
->get(['company_name', 'receipt_from_supplier']);
->get($columns);
foreach ($rows as $row) {
$overrides[(string) $row->company_name] = $this->nullableAmount($row->receipt_from_supplier);
$values = [
'receipt_from_supplier' => $this->nullableAmount($row->receipt_from_supplier),
];
if (in_array('receipt_from_suofeiya', $columns, true)) {
$values['receipt_from_suofeiya'] = $this->nullableAmount($row->receipt_from_suofeiya);
}
$overrides[(string) $row->company_name] = $values;
}
}

View File

@ -35,6 +35,9 @@
$internalFlowProjection['source_month_label']
?? now()->startOfMonth()->subMonthNoOverflow()->format('n') . '月'
);
$internalFlowCostToIncomeRules = $isInternalFlowReportPage
? (array) config('internal_flow_report.cost_to_income', [])
: [];
// “最近三个月销量”必须是三个独立的月份列;月份按当前月向前取三个完整月份。
// 保留原字段名作为兼容契约,渲染时展开为 *_1、*_2、*_3 三个值。
$directoryFields = collect($directoryFields)->flatMap(function (array $field): array {
@ -1622,7 +1625,7 @@
@elseif ($isInternalFlowReportPage && $directoryTotal > 0)
<div class="directory-table-notice" role="status">
<span class="material-icons-outlined" aria-hidden="true">calculate</span>
<span>预计{{ $internalFlowForecastMonthLabel }}销量取自主体维度经营报表{{ $internalFlowSourceMonthLabel }}业绩;买家开票按 20%、内部开票额度按 25%、所需进项成本按 80% 计算。内部开票按标签 1→2→3→4 顺延,并按下一标签公司剩余进项成本占比分配,票不足时计入剩余缺口。收票-供应商可直接填写并保存。</span>
<span>预计{{ $internalFlowForecastMonthLabel }}销量取自主体维度经营报表{{ $internalFlowSourceMonthLabel }}业绩;买家开票按 20%、内部开票额度按 25%、所需进项成本按 80% 计算。心选可按索菲亚收票金额倒推收入:收入 = 金额 ÷ 90%,心选内部开票按全额收入计算。内部开票按标签 1→2→3→4 顺延,票不足时计入剩余缺口。</span>
</div>
@elseif ($directoryTotal > 0 && in_array($directoryPageKey, ['store-management/store-accounts', 'store-management/store-report', 'company-management/subject-operating-report', 'company-management/company-cost-arrangement', 'company-management/personnel-inventory'], true))
<div class="directory-table-notice" role="status">
@ -3118,6 +3121,8 @@
@php
$source = array_key_exists('source', $field) ? $field['source'] : $field['name'];
$value = $source ? data_get($row, $source) : null;
$companyName = trim((string) data_get($row, 'company_name', ''));
$manualReceiptRule = $internalFlowCostToIncomeRules[$companyName] ?? null;
$kind = $field['kind'] ?? 'text';
$display = $value;
if ($kind === 'secret') {
@ -3165,12 +3170,30 @@
<button type="button" data-store-password-copy hidden aria-label="复制{{ data_get($row, 'store_name') }}的账号密码">复制</button>
</span>
@endif
@elseif ($isInternalFlowReportPage && $field['name'] === 'receipt_from_supplier')
@elseif (
$isInternalFlowReportPage
&& (
$field['name'] === 'receipt_from_supplier'
|| (
is_array($manualReceiptRule)
&& $field['name'] === ($manualReceiptRule['receipt_field'] ?? null)
)
)
)
@php
$receiptField = $field['name'];
$isSuofeiyaReceipt = $receiptField === 'receipt_from_suofeiya';
$receiptLabel = $isSuofeiyaReceipt ? '收票-索菲亚' : '收票-供应商';
$receiptRoute = $isSuofeiyaReceipt
? 'business.internal-flow-report.suofeiya-receipt'
: 'business.internal-flow-report.supplier-receipt';
@endphp
<form
method="POST"
action="{{ route('business.internal-flow-report.supplier-receipt', ['record' => data_get($row, 'id')]) }}"
action="{{ route($receiptRoute, ['record' => data_get($row, 'id')]) }}"
class="internal-flow-supplier-form"
data-internal-flow-supplier-form
data-internal-flow-receipt-form
data-receipt-field="{{ $receiptField }}"
>
@csrf
@method('PATCH')
@ -3178,16 +3201,16 @@
<input type="hidden" name="tag" value="{{ request('tag') }}">
<input
type="number"
name="receipt_from_supplier"
name="{{ $receiptField }}"
min="0"
step="0.01"
inputmode="decimal"
value="{{ is_numeric($value) ? number_format((float) $value, 2, '.', '') : '' }}"
aria-label="{{ data_get($row, 'company_name') }}收票-供应商"
data-internal-flow-supplier-input
aria-label="{{ $companyName }}{{ $receiptLabel }}"
data-internal-flow-receipt-input
>
<button type="submit" data-internal-flow-supplier-save>保存</button>
<span class="internal-flow-supplier-status" data-internal-flow-supplier-status aria-live="polite"></span>
<button type="submit" data-internal-flow-receipt-save>保存</button>
<span class="internal-flow-supplier-status" data-internal-flow-receipt-status aria-live="polite"></span>
</form>
@else
@if ($kind === 'badge' && filled($display))
@ -3750,7 +3773,7 @@
const exportCellText = (cell) => {
const passwordStatus = cell?.querySelector('[data-password-status]');
if (passwordStatus) return passwordStatus.textContent.trim();
const editable = cell?.querySelector('[data-internal-flow-supplier-input]');
const editable = cell?.querySelector('[data-internal-flow-receipt-input]');
if (editable) return String(editable.value || '').trim();
return String(cell?.textContent || '').trim();
@ -4515,10 +4538,11 @@
row.addEventListener('keydown', (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); render(); } });
});
document.querySelectorAll('[data-internal-flow-supplier-form]').forEach((form) => {
const input = form.querySelector('[data-internal-flow-supplier-input]');
const button = form.querySelector('[data-internal-flow-supplier-save]');
const status = form.querySelector('[data-internal-flow-supplier-status]');
document.querySelectorAll('[data-internal-flow-receipt-form]').forEach((form) => {
const input = form.querySelector('[data-internal-flow-receipt-input]');
const button = form.querySelector('[data-internal-flow-receipt-save]');
const status = form.querySelector('[data-internal-flow-receipt-status]');
const receiptField = form.dataset.receiptField || 'receipt_from_supplier';
const row = form.closest('tr');
if (!input || !button || !status || !row) return;
@ -4576,15 +4600,16 @@
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
const validation = payload.errors?.receipt_from_supplier?.[0];
const validation = payload.errors?.[receiptField]?.[0];
throw new Error(validation || payload.message || '保存失败,请稍后重试。');
}
const record = payload.record || {};
input.value = record.receipt_from_supplier === null
|| record.receipt_from_supplier === undefined
const receiptAmount = record.receipt_amount ?? record[receiptField];
input.value = receiptAmount === null
|| receiptAmount === undefined
? ''
: Number(record.receipt_from_supplier).toFixed(2);
: Number(receiptAmount).toFixed(2);
form.dataset.initialValue = input.value;
updateAmountCell('receipt_total', record.receipt_total);
updateAmountCell('remaining_gap', record.remaining_gap);
@ -4593,10 +4618,21 @@
`tr[data-internal-flow-row-id="${CSS.escape(String(updatedRow.id))}"]`
);
if (!targetRow) return;
['internal_transfer_1', 'internal_transfer_2', 'internal_transfer_3', 'receipt_total', 'remaining_gap']
[
'projected_sales',
'invoiced_to_buyer',
'internal_invoiced',
'required_input_cost',
'internal_transfer_1',
'internal_transfer_2',
'internal_transfer_3',
'receipt_total',
'remaining_gap',
]
.forEach((field) => updateAmountCellFor(targetRow, field, updatedRow[field]));
});
const summary = payload.summary || {};
updateSummaryCard('预计销量合计', summary.projected_sales);
updateSummaryCard('已收票合计', summary.receipt_total);
updateSummaryCard('剩余缺口合计', summary.remaining_gap);
if (payload.warning) {

View File

@ -964,6 +964,14 @@ Route::middleware('business.page.viewer')->group(function (): void {
->middleware('business.page:store-management,internal-flow-report')
->name('business.internal-flow-report.supplier-receipt');
Route::patch(
'workspace/store-management/internal-flow-report/{record}/suofeiya-receipt',
[InternalFlowReportActions::class, 'updateSuofeiyaReceipt'],
)
->whereNumber('record')
->middleware('business.page:store-management,internal-flow-report')
->name('business.internal-flow-report.suofeiya-receipt');
Route::patch('workspace/{section}/{page}/{id}/{tab?}', 'Business\Pages@update')
->name('business.pages.update');

View File

@ -30,7 +30,7 @@ class InternalFlowReportPageTest extends FeatureTestCase
'forecast_month_label' => '11月',
'source_month' => '2026-10',
'source_month_label' => '10月',
'sales_by_company' => ['示例甲供应链有限公司' => 1200000.0],
'sales_by_company' => ['常州心选供应链有限公司' => 1200000.0],
]);
$this->app->instance(InternalFlowProjection::class, $projection);
@ -40,14 +40,14 @@ class InternalFlowReportPageTest extends FeatureTestCase
'data' => [[
'id' => 1,
'sort_order' => 1,
'company_name' => '示例甲供应链有限公司',
'company_name' => '常州心选供应链有限公司',
'tag' => '1',
'projected_sales' => '1200000.000000',
'invoiced_to_buyer' => '240000.000000',
'internal_invoiced' => '300000.000000',
'required_input_cost' => '960000.000000',
'receipt_from_supplier' => '100000.000000',
'receipt_from_suofeiya' => null,
'receipt_from_suofeiya' => '900000.000000',
'receipt_from_gujia' => null,
'internal_transfer_1' => '0.000000',
'internal_transfer_2' => '0.000000',
@ -75,12 +75,15 @@ class InternalFlowReportPageTest extends FeatureTestCase
->assertOk()
->assertSeeText('内部流转报表')
->assertSeeText('按抬头、标签查询内部流转明细并导出')
->assertSeeText('示例甲供应链有限公司')
->assertSeeText('常州心选供应链有限公司')
->assertSeeText('预计11月销量')
->assertSeeText('取自主体维度经营报表10月业绩')
->assertSeeText('内部开票按标签 1→2→3→4 顺延')
->assertSeeText('票不足时计入剩余缺口')
->assertSee('data-internal-flow-supplier-input', false)
->assertSee('data-internal-flow-receipt-input', false)
->assertSee('data-receipt-field="receipt_from_suofeiya"', false)
->assertSee('suofeiya-receipt', false)
->assertSee('value="900000.00"', false)
->assertSee('data-internal-flow-row-id="1"', false)
->assertSee('value="100000.00"', false)
->assertSeeText('收票-内部流转(来源)1')
@ -115,9 +118,9 @@ class InternalFlowReportPageTest extends FeatureTestCase
$this->app->instance(InternalFlowProjection::class, $projection);
$repository = Mockery::mock(InternalFlowReportRepository::class);
$repository->shouldReceive('updateSupplierReceipt')
$repository->shouldReceive('updateReceiptOverride')
->once()
->with(7, 500000.0, (int) $this->user->id)
->with(7, 'receipt_from_supplier', 500000.0, (int) $this->user->id)
->andReturn('示例甲供应链有限公司');
$repository->shouldReceive('paginate')
->once()
@ -154,13 +157,115 @@ class InternalFlowReportPageTest extends FeatureTestCase
)
->assertOk()
->assertJsonPath('ok', true)
->assertJsonPath('record.receipt_from_supplier', 500000)
->assertJsonPath('record.receipt_field', 'receipt_from_supplier')
->assertJsonPath('record.receipt_amount', 500000)
->assertJsonPath('record.receipt_total', 500000)
->assertJsonPath('record.remaining_gap', 460000)
->assertJsonPath('rows.0.internal_transfer_2', 250000)
->assertJsonPath('summary.receipt_total', 500000);
}
public function testXinxuanSuofeiyaReceiptUsesCostToIncomeFormulaAndReturnsAllRows(): void
{
$projectionPayload = [
'forecast_month' => '2026-11',
'forecast_month_label' => '11月',
'source_month' => '2026-10',
'source_month_label' => '10月',
'sales_by_company' => [],
];
$projection = Mockery::mock(InternalFlowProjection::class);
$projection->shouldReceive('forMonth')->once()->andReturn($projectionPayload);
$this->app->instance(InternalFlowProjection::class, $projection);
$repository = Mockery::mock(InternalFlowReportRepository::class);
$repository->shouldReceive('companyNameForRecord')
->once()
->with(8)
->andReturn('常州心选供应链有限公司');
$repository->shouldReceive('updateReceiptOverride')
->once()
->with(8, 'receipt_from_suofeiya', 900000.0, (int) $this->user->id)
->andReturn('常州心选供应链有限公司');
$repository->shouldReceive('paginate')
->once()
->with(1, 100, ['company_name' => '', 'tag' => ''], null, 'asc', $projectionPayload)
->andReturn([
'data' => [
[
'id' => 8,
'projected_sales' => 1000000.0,
'invoiced_to_buyer' => 200000.0,
'internal_invoiced' => 1000000.0,
'required_input_cost' => 900000.0,
'receipt_from_suofeiya' => 900000.0,
'internal_transfer_1' => 0.0,
'internal_transfer_2' => 0.0,
'internal_transfer_3' => 0.0,
'receipt_total' => 900000.0,
'remaining_gap' => 0.0,
],
[
'id' => 9,
'projected_sales' => 2000000.0,
'invoiced_to_buyer' => 400000.0,
'internal_invoiced' => 500000.0,
'required_input_cost' => 1600000.0,
'internal_transfer_1' => 1000000.0,
'internal_transfer_2' => 0.0,
'internal_transfer_3' => 0.0,
'receipt_total' => 1000000.0,
'remaining_gap' => 600000.0,
],
],
'total' => 2,
'summary' => [
'companies' => 2,
'projected_sales' => 3000000.0,
'receipt_total' => 1900000.0,
'remaining_gap' => 600000.0,
'average_invoicing_ratio' => 0.0,
],
]);
$this->app->instance(InternalFlowReportRepository::class, $repository);
$this->loginAs()
->patchJson(
route('business.internal-flow-report.suofeiya-receipt', ['record' => 8]),
[
'receipt_from_suofeiya' => '900000',
'company_name' => '',
'tag' => '',
],
)
->assertOk()
->assertJsonPath('record.receipt_field', 'receipt_from_suofeiya')
->assertJsonPath('record.receipt_amount', 900000)
->assertJsonPath('record.projected_sales', 1000000)
->assertJsonPath('rows.0.internal_invoiced', 1000000)
->assertJsonPath('rows.1.internal_transfer_1', 1000000)
->assertJsonPath('summary.projected_sales', 3000000);
}
public function testSuofeiyaReceiptIsRejectedForOtherCompanies(): void
{
$repository = Mockery::mock(InternalFlowReportRepository::class);
$repository->shouldReceive('companyNameForRecord')
->once()
->with(8)
->andReturn('其他公司有限公司');
$this->app->instance(InternalFlowReportRepository::class, $repository);
$this->withExceptionHandling();
$this->loginAs()
->patchJson(
route('business.internal-flow-report.suofeiya-receipt', ['record' => 8]),
['receipt_from_suofeiya' => '900000'],
)
->assertForbidden();
}
public function testInternalFlowReportPageExplainsMissingDataset(): void
{
$repository = Mockery::mock(InternalFlowReportRepository::class);

View File

@ -33,6 +33,10 @@ class InternalFlowReportImportTest extends TestCase
'database/migrations/2026_11_09_200000_create_internal_flow_supplier_receipt_overrides_table.php'
);
$overridesMigration->up();
$suofeiyaMigration = require base_path(
'database/migrations/2026_11_09_210000_add_suofeiya_receipt_to_internal_flow_overrides.php'
);
$suofeiyaMigration->up();
}
public function testImportKeepsWorkbookValuesAndSkipsTotalRows(): void
@ -293,6 +297,48 @@ class InternalFlowReportImportTest extends TestCase
);
}
public function testXinxuanSuofeiyaCostReversesIncomeAndUsesFullInternalInvoiceCapacity(): void
{
$rows = [
['常州心选供应链有限公司', 1, 0, 0, 0, 0, null, null, null, 0, 0, 0, 0, null, '/'],
['标签二有限公司', 2, 2000000, 0, 500000, 1600000, 0, null, null, 0, 0, 0, 0, 1600000, 1],
];
$path = $this->writeWorkbook($rows);
app(InternalFlowWorkbookImporter::class)->import($path);
@unlink($path);
$xinxuanId = (int) DB::connection('business_mirror')
->table(InternalFlowWorkbookImporter::TABLE)
->where('company_name', '常州心选供应链有限公司')
->value('id');
$repository = app(InternalFlowReportRepository::class);
$repository->updateSuofeiyaReceipt($xinxuanId, 900000.0, 99);
$projection = [
'forecast_month' => '2026-11',
'forecast_month_label' => '11月',
'source_month' => '2026-10',
'source_month_label' => '10月',
'sales_by_company' => [
'标签二有限公司' => 2000000.0,
],
];
$result = $repository->paginate(1, 50, [], null, 'asc', $projection);
$byCompany = collect($result['data'])->keyBy('company_name');
$xinxuan = $byCompany['常州心选供应链有限公司'];
$tagTwo = $byCompany['标签二有限公司'];
$this->assertEqualsWithDelta(900000.0, $xinxuan['required_input_cost'], 0.000001);
$this->assertEqualsWithDelta(1000000.0, $xinxuan['projected_sales'], 0.000001);
$this->assertEqualsWithDelta(200000.0, $xinxuan['invoiced_to_buyer'], 0.000001);
$this->assertEqualsWithDelta(1000000.0, $xinxuan['internal_invoiced'], 0.000001);
$this->assertEqualsWithDelta(900000.0, $xinxuan['receipt_total'], 0.000001);
$this->assertEqualsWithDelta(0.0, $xinxuan['remaining_gap'], 0.000001);
$this->assertEqualsWithDelta(1000000.0, $tagTwo['internal_transfer_1'], 0.000001);
$this->assertEqualsWithDelta(600000.0, $tagTwo['remaining_gap'], 0.000001);
$this->assertEqualsWithDelta(3000000.0, $result['summary']['projected_sales'], 0.000001);
}
/**
* @return list<list<mixed>>
*/