feat: 增加人工费用数据保存功能 #770
141
app/Business/LaborExpenseDataStore.php
Normal file
141
app/Business/LaborExpenseDataStore.php
Normal file
@ -0,0 +1,141 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business;
|
||||
|
||||
use App\Models\Business\LaborExpenseSnapshot;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class LaborExpenseDataStore
|
||||
{
|
||||
public const MAX_ROWS = 2000;
|
||||
|
||||
/**
|
||||
* @return array{rows: array<int, array<string, mixed>>, row_count: int, source_name: ?string, saved_by: ?int, saved_at: ?string}
|
||||
*/
|
||||
public function load(): array
|
||||
{
|
||||
$snapshot = LaborExpenseSnapshot::query()
|
||||
->where('company_id', company_id())
|
||||
->first();
|
||||
|
||||
return [
|
||||
'rows' => is_array($snapshot?->rows) ? array_values($snapshot->rows) : [],
|
||||
'row_count' => (int) ($snapshot?->row_count ?? 0),
|
||||
'source_name' => $snapshot?->source_name,
|
||||
'saved_by' => $snapshot?->saved_by,
|
||||
'saved_at' => $snapshot?->saved_at?->toIso8601String(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, mixed> $rows
|
||||
* @return array{rows: array<int, array<string, mixed>>, row_count: int, source_name: ?string, saved_by: ?int, saved_at: string}
|
||||
*/
|
||||
public function save(array $rows, ?string $sourceName, ?int $savedBy): array
|
||||
{
|
||||
if (count($rows) > self::MAX_ROWS) {
|
||||
throw ValidationException::withMessages([
|
||||
'rows' => '单次最多保存 ' . number_format(self::MAX_ROWS) . ' 行,请拆分后再保存。',
|
||||
]);
|
||||
}
|
||||
|
||||
$fields = collect(config('labor_expense_table.fields', []))
|
||||
->filter(static fn (array $field): bool => ($field['kind'] ?? null) !== 'sequence'
|
||||
&& blank($field['formula'] ?? null))
|
||||
->values();
|
||||
|
||||
if ($fields->isEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'rows' => '人工费用表没有可保存的录入列。',
|
||||
]);
|
||||
}
|
||||
|
||||
$companyId = (int) company_id();
|
||||
if ($companyId < 1) {
|
||||
throw ValidationException::withMessages([
|
||||
'rows' => '当前没有可保存的公司。',
|
||||
]);
|
||||
}
|
||||
|
||||
$normalizedRows = [];
|
||||
foreach (array_values($rows) as $index => $row) {
|
||||
if (! is_array($row)) {
|
||||
throw ValidationException::withMessages([
|
||||
'rows' => '第 ' . ($index + 1) . ' 行数据格式无效。',
|
||||
]);
|
||||
}
|
||||
|
||||
$record = [];
|
||||
$hasValue = false;
|
||||
foreach ($fields as $field) {
|
||||
$value = $this->normalizeCell($row[$field['key']] ?? null, $field, $index + 1);
|
||||
$record[$field['key']] = $value;
|
||||
$hasValue = $hasValue || $value !== '';
|
||||
}
|
||||
|
||||
if ($hasValue) {
|
||||
$normalizedRows[] = $record;
|
||||
}
|
||||
}
|
||||
|
||||
$sourceName = trim((string) $sourceName);
|
||||
$sourceName = $sourceName === '' ? null : mb_substr($sourceName, 0, 191);
|
||||
$savedAt = now();
|
||||
|
||||
DB::transaction(function () use ($companyId, $sourceName, $savedBy, $savedAt, $normalizedRows): void {
|
||||
LaborExpenseSnapshot::query()->updateOrCreate(
|
||||
['company_id' => $companyId],
|
||||
[
|
||||
'source_name' => $sourceName,
|
||||
'rows' => $normalizedRows,
|
||||
'row_count' => count($normalizedRows),
|
||||
'saved_by' => $savedBy,
|
||||
'saved_at' => $savedAt,
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
return [
|
||||
'rows' => $normalizedRows,
|
||||
'row_count' => count($normalizedRows),
|
||||
'source_name' => $sourceName,
|
||||
'saved_by' => $savedBy,
|
||||
'saved_at' => $savedAt->toIso8601String(),
|
||||
];
|
||||
}
|
||||
|
||||
private function normalizeCell(mixed $value, array $field, int $line): mixed
|
||||
{
|
||||
if ($value === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$text = trim((string) $value);
|
||||
if ($text === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (! in_array($field['kind'] ?? 'text', ['number', 'percent'], true)) {
|
||||
if (mb_strlen($text) > 120) {
|
||||
throw ValidationException::withMessages([
|
||||
'rows' => "第 {$line} 行“{$field['label']}”不能超过 120 个字符。",
|
||||
]);
|
||||
}
|
||||
|
||||
return $text;
|
||||
}
|
||||
|
||||
$isPercentText = ($field['kind'] ?? null) === 'percent' && str_ends_with($text, '%');
|
||||
$number = str_replace([',', ',', '¥', '¥', '%'], '', $text);
|
||||
if (! is_numeric($number)) {
|
||||
throw ValidationException::withMessages([
|
||||
'rows' => "第 {$line} 行“{$field['label']}”不是有效数字。",
|
||||
]);
|
||||
}
|
||||
|
||||
$normalized = (float) $number;
|
||||
|
||||
return $isPercentText ? $normalized / 100 : $normalized;
|
||||
}
|
||||
}
|
||||
@ -8,6 +8,7 @@ use App\Business\InventoryInboundDetailImporter;
|
||||
use App\Business\InventoryWarehouseNameMappingWorkbookImporter;
|
||||
use App\Business\InventoryWarehouseShortNames;
|
||||
use App\Business\LaborExpenseWorkbookImporter;
|
||||
use App\Business\LaborExpenseDataStore;
|
||||
use App\Business\CourierPayableSummaryFilter;
|
||||
use App\Business\CourierPayableSummaryStore;
|
||||
use App\Business\FundForecastTemplate;
|
||||
@ -4740,10 +4741,17 @@ class Pages extends Controller
|
||||
|
||||
protected function contentForLaborExpenses(): array
|
||||
{
|
||||
$saved = app(LaborExpenseDataStore::class)->load();
|
||||
$sessionRows = session('labor_expense_import_rows');
|
||||
$hasSessionRows = is_array($sessionRows);
|
||||
|
||||
return [
|
||||
'view' => 'business.pages.financial-operations.labor-expenses',
|
||||
'laborExpenseTable' => config('labor_expense_table'),
|
||||
'laborExpenseInitialRows' => session('labor_expense_import_rows', []),
|
||||
'laborExpenseInitialRows' => $hasSessionRows ? array_values($sessionRows) : $saved['rows'],
|
||||
'laborExpenseInitialDirty' => $hasSessionRows,
|
||||
'laborExpenseSavedAt' => $saved['saved_at'],
|
||||
'laborExpenseSourceName' => $saved['source_name'],
|
||||
'laborExpenseImportMessage' => session('labor_expense_import_message'),
|
||||
];
|
||||
}
|
||||
@ -4778,6 +4786,28 @@ class Pages extends Controller
|
||||
->with('labor_expense_import_message', $message);
|
||||
}
|
||||
|
||||
public function saveLaborExpenses(Request $request)
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'rows' => ['present', 'array', 'max:' . LaborExpenseDataStore::MAX_ROWS],
|
||||
'source_name' => ['nullable', 'string', 'max:191'],
|
||||
]);
|
||||
|
||||
$result = app(LaborExpenseDataStore::class)->save(
|
||||
$validated['rows'],
|
||||
$validated['source_name'] ?? null,
|
||||
auth()->id(),
|
||||
);
|
||||
$message = $result['row_count'] > 0
|
||||
? "保存成功:共 {$result['row_count']} 行。"
|
||||
: '保存成功:当前人工费用数据已清空。';
|
||||
|
||||
return response()->json([
|
||||
'message' => $message,
|
||||
...$result,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 税金预测表逻辑配置:规则清单、数据源状态和运行参数。
|
||||
*/
|
||||
|
||||
27
app/Models/Business/LaborExpenseSnapshot.php
Normal file
27
app/Models/Business/LaborExpenseSnapshot.php
Normal file
@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Business;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class LaborExpenseSnapshot extends Model
|
||||
{
|
||||
protected $table = 'business_labor_expense_snapshots';
|
||||
|
||||
protected $fillable = [
|
||||
'company_id',
|
||||
'source_name',
|
||||
'rows',
|
||||
'row_count',
|
||||
'saved_by',
|
||||
'saved_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'company_id' => 'integer',
|
||||
'rows' => 'array',
|
||||
'row_count' => 'integer',
|
||||
'saved_by' => 'integer',
|
||||
'saved_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('business_labor_expense_snapshots', function (Blueprint $table): void {
|
||||
$table->bigIncrements('id');
|
||||
$table->unsignedInteger('company_id');
|
||||
$table->string('source_name', 191)->nullable();
|
||||
$table->json('rows');
|
||||
$table->unsignedInteger('row_count')->default(0);
|
||||
$table->unsignedInteger('saved_by')->nullable();
|
||||
$table->timestamp('saved_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique('company_id', 'labor_expense_snapshots_company_unique');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('business_labor_expense_snapshots');
|
||||
}
|
||||
};
|
||||
@ -158,10 +158,30 @@
|
||||
color: #a22a2a;
|
||||
}
|
||||
|
||||
.labor-expense-import-status[data-state="pending"] {
|
||||
border-color: #dfd0ae;
|
||||
background: #fffaf0;
|
||||
color: var(--vip-content-accent-dark, #856632);
|
||||
}
|
||||
|
||||
.labor-expense-import-status[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.labor-expense-save-state {
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.7rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.labor-expense-save-state[data-state="dirty"] {
|
||||
color: var(--vip-warning, #935F07);
|
||||
}
|
||||
|
||||
.labor-expense-save-state[data-state="saved"] {
|
||||
color: var(--vip-success, #53793E);
|
||||
}
|
||||
|
||||
.labor-expense-table-wrap {
|
||||
border: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-radius: 0.5rem;
|
||||
@ -505,7 +525,7 @@
|
||||
|
||||
<div class="labor-expense-note" role="note">
|
||||
<span class="material-icons-outlined" aria-hidden="true">info</span>
|
||||
<div>页面不预置源表人员、花名或金额。可导入与当前表头一致的 xlsx、xls 或 csv;系统只读取黄色可录入列并自动重算公式。导入会替换当前页面已有行,数据不写入人员明细库,离开页面后清空。</div>
|
||||
<div>页面首次不预置源表人员、花名或金额。可导入与当前表头一致的 xlsx、xls 或 csv;系统只读取黄色可录入列并自动重算公式。导入或手工修改后请点击“保存数据”,保存后下次进入会自动加载;数据只保存在本测算表,不写入人员明细库。</div>
|
||||
</div>
|
||||
|
||||
<div class="finance-table-controls labor-expense-toolbar" data-finance-controls>
|
||||
@ -531,6 +551,16 @@
|
||||
导入 Excel/CSV
|
||||
</button>
|
||||
</form>
|
||||
<button
|
||||
type="button"
|
||||
class="finance-table-controls__button"
|
||||
data-labor-save
|
||||
data-labor-save-url="{{ route('business.labor-expenses.save', ['section' => 'financial-operations', 'page' => 'labor-expenses']) }}"
|
||||
>
|
||||
<span class="material-icons-outlined" aria-hidden="true">save</span>
|
||||
保存数据
|
||||
</button>
|
||||
<span class="labor-expense-save-state" data-labor-save-state>未保存</span>
|
||||
<button type="button" class="finance-table-controls__button" data-directory-export>
|
||||
<span class="material-icons-outlined" aria-hidden="true">download</span>
|
||||
导出当前显示列
|
||||
@ -620,8 +650,16 @@
|
||||
const importFile = root.querySelector('[data-labor-import-file]');
|
||||
const importOpen = root.querySelector('[data-labor-import-open]');
|
||||
const importStatus = root.querySelector('[data-labor-import-status]');
|
||||
const saveButton = root.querySelector('[data-labor-save]');
|
||||
const saveState = root.querySelector('[data-labor-save-state]');
|
||||
const csrfToken = importForm?.querySelector('input[name="_token"]')?.value ?? '';
|
||||
let rows = @json($laborExpenseInitialRows);
|
||||
if (!Array.isArray(rows) || rows.length === 0) rows = [{}];
|
||||
let sourceName = @json($laborExpenseSourceName ?? null);
|
||||
let lastSavedAt = @json($laborExpenseSavedAt ?? null);
|
||||
let isDirty = @json((bool) ($laborExpenseInitialDirty ?? false));
|
||||
let isSaving = false;
|
||||
const editableFields = fields.filter((field) => field.kind !== 'sequence' && !field.formula);
|
||||
|
||||
const moneyFormatter = new Intl.NumberFormat('zh-CN', {
|
||||
minimumFractionDigits: 2,
|
||||
@ -1058,6 +1096,54 @@
|
||||
return value;
|
||||
};
|
||||
|
||||
const formatSavedAt = (value) => {
|
||||
if (!value) return '';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
|
||||
return new Intl.DateTimeFormat('zh-CN', {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}).format(date);
|
||||
};
|
||||
|
||||
const updateSaveState = () => {
|
||||
if (!saveState || !saveButton) return;
|
||||
saveButton.disabled = isSaving;
|
||||
if (isSaving) {
|
||||
saveState.textContent = '正在保存…';
|
||||
saveState.dataset.state = 'dirty';
|
||||
return;
|
||||
}
|
||||
if (isDirty) {
|
||||
saveState.textContent = '有未保存更改';
|
||||
saveState.dataset.state = 'dirty';
|
||||
return;
|
||||
}
|
||||
|
||||
const savedTime = formatSavedAt(lastSavedAt);
|
||||
saveState.textContent = savedTime ? `已保存 ${savedTime}` : '未保存';
|
||||
saveState.dataset.state = savedTime ? 'saved' : '';
|
||||
};
|
||||
|
||||
const markDirty = () => {
|
||||
isDirty = true;
|
||||
updateSaveState();
|
||||
};
|
||||
|
||||
const markSaved = (savedAt) => {
|
||||
isDirty = false;
|
||||
lastSavedAt = savedAt || new Date().toISOString();
|
||||
updateSaveState();
|
||||
};
|
||||
|
||||
const editableRowsPayload = () => rows.map((row) => Object.fromEntries(
|
||||
editableFields.map((field) => [field.key, row?.[field.key] ?? ''])
|
||||
));
|
||||
|
||||
tbody.addEventListener('input', (event) => {
|
||||
const input = event.target.closest('[data-labor-field]');
|
||||
if (!input) return;
|
||||
@ -1071,6 +1157,7 @@
|
||||
input.closest('td').dataset.exportValue = exportValue;
|
||||
updateOutputs(rowElement, index);
|
||||
updateSummary();
|
||||
markDirty();
|
||||
});
|
||||
|
||||
tbody.addEventListener('click', (event) => {
|
||||
@ -1080,6 +1167,7 @@
|
||||
if (!Number.isInteger(index)) return;
|
||||
rows.splice(index, 1);
|
||||
renderRows();
|
||||
markDirty();
|
||||
});
|
||||
|
||||
root.querySelector('[data-labor-add]')?.addEventListener('click', () => {
|
||||
@ -1087,12 +1175,14 @@
|
||||
renderRows();
|
||||
const lastRow = tbody.querySelector(`tr[data-labor-row="${rows.length - 1}"]`);
|
||||
lastRow?.querySelector('[data-labor-field="B"]')?.focus();
|
||||
markDirty();
|
||||
});
|
||||
|
||||
root.querySelector('[data-labor-reset]')?.addEventListener('click', () => {
|
||||
rows = [{}];
|
||||
renderRows();
|
||||
tbody.querySelector('[data-labor-field="B"]')?.focus();
|
||||
markDirty();
|
||||
});
|
||||
|
||||
const setImportStatus = (message, state = 'success') => {
|
||||
@ -1102,6 +1192,16 @@
|
||||
importStatus.hidden = message === '';
|
||||
};
|
||||
|
||||
const responseErrorMessage = (response, payload, fallback) => {
|
||||
if (response.status === 429) return '操作过于频繁,请等待 1 分钟后重试。';
|
||||
if (response.status === 419) return '页面登录状态已过期,请刷新页面后重试。';
|
||||
const validationMessage = payload.errors
|
||||
? Object.values(payload.errors).flat().find(Boolean)
|
||||
: null;
|
||||
|
||||
return validationMessage || payload.message || fallback;
|
||||
};
|
||||
|
||||
importOpen?.addEventListener('click', () => {
|
||||
const hasEnteredRows = rows.some((row) => Object.values(row).some((value) => (
|
||||
value !== '' && value !== null && value !== undefined
|
||||
@ -1113,8 +1213,9 @@
|
||||
importFile?.addEventListener('change', async () => {
|
||||
if (!importForm || !importFile.files?.length) return;
|
||||
|
||||
const importedSourceName = importFile.files[0]?.name ?? sourceName;
|
||||
importOpen.disabled = true;
|
||||
setImportStatus('正在读取文件并重算公式…');
|
||||
setImportStatus('正在读取文件并重算公式…', 'pending');
|
||||
|
||||
try {
|
||||
const response = await fetch(importForm.action, {
|
||||
@ -1129,15 +1230,21 @@
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
|
||||
if (!response.ok) {
|
||||
const validationMessage = payload.errors
|
||||
? Object.values(payload.errors).flat().find(Boolean)
|
||||
: null;
|
||||
throw new Error(validationMessage || payload.message || '导入失败,请检查文件表头和数据。');
|
||||
throw new Error(responseErrorMessage(
|
||||
response,
|
||||
payload,
|
||||
'导入失败,请检查文件表头和数据。'
|
||||
));
|
||||
}
|
||||
|
||||
rows = Array.isArray(payload.rows) && payload.rows.length ? payload.rows : [{}];
|
||||
sourceName = importedSourceName;
|
||||
renderRows();
|
||||
setImportStatus(payload.message || `导入完成:共 ${rows.length} 行。`);
|
||||
markDirty();
|
||||
setImportStatus(
|
||||
`${payload.message || `导入完成:共 ${rows.length} 行。`} 尚未保存,请点击“保存数据”写入系统。`,
|
||||
'pending'
|
||||
);
|
||||
} catch (error) {
|
||||
setImportStatus(error instanceof Error ? error.message : '导入失败,请稍后重试。', 'error');
|
||||
} finally {
|
||||
@ -1146,10 +1253,57 @@
|
||||
}
|
||||
});
|
||||
|
||||
saveButton?.addEventListener('click', async () => {
|
||||
if (isSaving || !saveButton.dataset.laborSaveUrl) return;
|
||||
|
||||
isSaving = true;
|
||||
updateSaveState();
|
||||
setImportStatus('正在保存人工费用数据…', 'pending');
|
||||
|
||||
try {
|
||||
const response = await fetch(saveButton.dataset.laborSaveUrl, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': csrfToken,
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
rows: editableRowsPayload(),
|
||||
source_name: sourceName,
|
||||
}),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(responseErrorMessage(response, payload, '保存失败,请稍后重试。'));
|
||||
}
|
||||
|
||||
rows = Array.isArray(payload.rows) && payload.rows.length ? payload.rows : [{}];
|
||||
sourceName = payload.source_name ?? sourceName;
|
||||
renderRows();
|
||||
markSaved(payload.saved_at);
|
||||
setImportStatus(payload.message || `保存成功:共 ${payload.row_count ?? 0} 行。`);
|
||||
} catch (error) {
|
||||
setImportStatus(error instanceof Error ? error.message : '保存失败,请稍后重试。', 'error');
|
||||
} finally {
|
||||
isSaving = false;
|
||||
updateSaveState();
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('beforeunload', (event) => {
|
||||
if (!isDirty) return;
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
});
|
||||
|
||||
window.addEventListener('resize', () => {
|
||||
window.requestAnimationFrame(updateFixedColumnOffsets);
|
||||
});
|
||||
|
||||
updateSaveState();
|
||||
renderRows();
|
||||
})();
|
||||
</script>
|
||||
|
||||
@ -861,6 +861,13 @@ Route::middleware('business.page.viewer')->group(function (): void {
|
||||
Route::get('workspace/{section}/{page?}/{tab?}', 'Business\Pages@show')
|
||||
->name('business.pages.show');
|
||||
|
||||
Route::post('workspace/{section}/{page}/save', 'Business\Pages@saveLaborExpenses')
|
||||
->where([
|
||||
'section' => 'financial-operations',
|
||||
'page' => 'labor-expenses',
|
||||
])
|
||||
->name('business.labor-expenses.save');
|
||||
|
||||
Route::post('workspace/{section}/{page}/import/{tab?}', 'Business\Pages@import')
|
||||
->middleware('import')
|
||||
->name('business.pages.import');
|
||||
|
||||
@ -2,11 +2,13 @@
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use App\Business\LaborExpenseDataStore;
|
||||
use App\Models\Auth\Permission;
|
||||
use App\Models\Auth\Role;
|
||||
use App\Models\Auth\User;
|
||||
use App\Utilities\SidebarPermissions;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
@ -66,6 +68,8 @@ class LaborExpensePageAccessTest extends FeatureTestCase
|
||||
->assertForbidden();
|
||||
$this->post(route('business.pages.import', $routeParameters), [])
|
||||
->assertForbidden();
|
||||
$this->post(route('business.labor-expenses.save', $routeParameters), ['rows' => []])
|
||||
->assertForbidden();
|
||||
|
||||
$this->withExceptionHandling()->loginAs($this->user)
|
||||
->get(route('business.pages.show', $routeParameters))
|
||||
@ -180,6 +184,108 @@ class LaborExpensePageAccessTest extends FeatureTestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_labor_expense_rows_can_be_saved_and_reloaded(): void
|
||||
{
|
||||
$chenxi = $this->account('晨曦');
|
||||
$routeParameters = [
|
||||
'section' => 'financial-operations',
|
||||
'page' => 'labor-expenses',
|
||||
];
|
||||
$response = $this->withExceptionHandling()
|
||||
->loginAs($chenxi)
|
||||
->withHeaders(['Accept' => 'application/json'])
|
||||
->post(route('business.labor-expenses.save', $routeParameters), [
|
||||
'source_name' => '8月工资.xlsx',
|
||||
'rows' => [[
|
||||
'A' => '1',
|
||||
'B' => '测试花名',
|
||||
'C' => '测试姓名',
|
||||
'D' => '测试中心',
|
||||
'E' => '测试职位',
|
||||
'F' => 10000.5,
|
||||
'G' => 800,
|
||||
'H' => 500,
|
||||
'J' => 999,
|
||||
]],
|
||||
]);
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('row_count', 1)
|
||||
->assertJsonPath('source_name', '8月工资.xlsx')
|
||||
->assertJsonPath('rows.0.B', '测试花名')
|
||||
->assertJsonPath('rows.0.C', '测试姓名')
|
||||
->assertJsonPath('rows.0.F', 10000.5)
|
||||
->assertJsonMissingPath('rows.0.J');
|
||||
|
||||
$snapshot = DB::table('business_labor_expense_snapshots')
|
||||
->where('company_id', $this->company->id)
|
||||
->first();
|
||||
$this->assertNotNull($snapshot);
|
||||
$this->assertSame(1, (int) $snapshot->row_count);
|
||||
$this->assertSame('8月工资.xlsx', $snapshot->source_name);
|
||||
$this->assertSame(
|
||||
[[
|
||||
'B' => '测试花名',
|
||||
'C' => '测试姓名',
|
||||
'D' => '测试中心',
|
||||
'E' => '测试职位',
|
||||
'F' => 10000.5,
|
||||
'G' => 800,
|
||||
'H' => 500,
|
||||
'BI' => '',
|
||||
]],
|
||||
json_decode($snapshot->rows, true, 512, JSON_THROW_ON_ERROR),
|
||||
);
|
||||
|
||||
$loaded = app(LaborExpenseDataStore::class)->load();
|
||||
$this->assertSame(1, $loaded['row_count']);
|
||||
$this->assertSame('8月工资.xlsx', $loaded['source_name']);
|
||||
$this->assertSame('测试花名', $loaded['rows'][0]['B']);
|
||||
|
||||
$this->loginAs($chenxi)
|
||||
->get(route('business.pages.show', $routeParameters))
|
||||
->assertOk()
|
||||
->assertSee('data-labor-save', false)
|
||||
->assertSee('data-labor-save-state', false);
|
||||
|
||||
$this->withExceptionHandling()
|
||||
->loginAs($chenxi)
|
||||
->withHeaders(['Accept' => 'application/json'])
|
||||
->post(route('business.labor-expenses.save', $routeParameters), [
|
||||
'rows' => [],
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonPath('row_count', 0)
|
||||
->assertJsonPath('rows', []);
|
||||
$this->assertDatabaseHas('business_labor_expense_snapshots', [
|
||||
'company_id' => $this->company->id,
|
||||
'row_count' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_labor_expense_save_rejects_invalid_numeric_values(): void
|
||||
{
|
||||
$chenxi = $this->account('晨曦');
|
||||
$response = $this->withExceptionHandling()
|
||||
->loginAs($chenxi)
|
||||
->withHeaders(['Accept' => 'application/json'])
|
||||
->post(route('business.labor-expenses.save', [
|
||||
'section' => 'financial-operations',
|
||||
'page' => 'labor-expenses',
|
||||
]), [
|
||||
'rows' => [[
|
||||
'B' => '测试花名',
|
||||
'F' => '不是数字',
|
||||
]],
|
||||
]);
|
||||
|
||||
$response->assertUnprocessable()
|
||||
->assertJsonValidationErrors('rows');
|
||||
$this->assertDatabaseMissing('business_labor_expense_snapshots', [
|
||||
'company_id' => $this->company->id,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_labor_expense_workbook_import_returns_editable_rows(): void
|
||||
{
|
||||
$chenxi = $this->account('晨曦');
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user