diff --git a/app/Http/Controllers/Business/InternalFlowReportActions.php b/app/Http/Controllers/Business/InternalFlowReportActions.php index 72537600..36e6863f 100644 --- a/app/Http/Controllers/Business/InternalFlowReportActions.php +++ b/app/Http/Controllers/Business/InternalFlowReportActions.php @@ -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, ); } } diff --git a/config/internal_flow_report.php b/config/internal_flow_report.php new file mode 100644 index 00000000..aa787b52 --- /dev/null +++ b/config/internal_flow_report.php @@ -0,0 +1,15 @@ + [ + '常州心选供应链有限公司' => [ + 'receipt_field' => 'receipt_from_suofeiya', + 'cost_to_income_rate' => 0.90, + 'internal_invoice_rate' => 1.00, + ], + ], +]; diff --git a/database/migrations/2026_11_09_210000_add_suofeiya_receipt_to_internal_flow_overrides.php b/database/migrations/2026_11_09_210000_add_suofeiya_receipt_to_internal_flow_overrides.php new file mode 100644 index 00000000..9c768e23 --- /dev/null +++ b/database/migrations/2026_11_09_210000_add_suofeiya_receipt_to_internal_flow_overrides.php @@ -0,0 +1,39 @@ +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'); + }); + } + } +}; diff --git a/modules/EcommerceFinance/Repositories/InternalFlowReportRepository.php b/modules/EcommerceFinance/Repositories/InternalFlowReportRepository.php index 8c3e1f10..fdc58ae0 100644 --- a/modules/EcommerceFinance/Repositories/InternalFlowReportRepository.php +++ b/modules/EcommerceFinance/Repositories/InternalFlowReportRepository.php @@ -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 $companyNames - * @return array + * @return array> */ 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; } } diff --git a/resources/views/business/pages/partials/directory-table.blade.php b/resources/views/business/pages/partials/directory-table.blade.php index 47aada8e..9f285ca6 100644 --- a/resources/views/business/pages/partials/directory-table.blade.php +++ b/resources/views/business/pages/partials/directory-table.blade.php @@ -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)
- 预计{{ $internalFlowForecastMonthLabel }}销量取自主体维度经营报表{{ $internalFlowSourceMonthLabel }}业绩;买家开票按 20%、内部开票额度按 25%、所需进项成本按 80% 计算。内部开票按标签 1→2→3→4 顺延,并按下一标签公司剩余进项成本占比分配,票不足时计入剩余缺口。收票-供应商可直接填写并保存。 + 预计{{ $internalFlowForecastMonthLabel }}销量取自主体维度经营报表{{ $internalFlowSourceMonthLabel }}业绩;买家开票按 20%、内部开票额度按 25%、所需进项成本按 80% 计算。心选可按索菲亚收票金额倒推收入:收入 = 金额 ÷ 90%,心选内部开票按全额收入计算。内部开票按标签 1→2→3→4 顺延,票不足时计入剩余缺口。
@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))
@@ -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 @@ @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
@csrf @method('PATCH') @@ -3178,16 +3201,16 @@ - - + +
@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) { diff --git a/routes/admin.php b/routes/admin.php index 3185806d..79b1adc6 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -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'); diff --git a/tests/Feature/Business/InternalFlowReportPageTest.php b/tests/Feature/Business/InternalFlowReportPageTest.php index da68b092..a6e4f96d 100644 --- a/tests/Feature/Business/InternalFlowReportPageTest.php +++ b/tests/Feature/Business/InternalFlowReportPageTest.php @@ -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); diff --git a/tests/Feature/Console/InternalFlowReportImportTest.php b/tests/Feature/Console/InternalFlowReportImportTest.php index 63585c1e..f2b249a5 100644 --- a/tests/Feature/Console/InternalFlowReportImportTest.php +++ b/tests/Feature/Console/InternalFlowReportImportTest.php @@ -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> */