Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
4da96f1
feat: 仕切書・定期請求スケジュールのコア実装 (Phase A) (#54)
strnh Jul 8, 2026
29b855f
feat: 仕切書 API と請求予定データ取得 API を追加 (Phase B) (#54)
strnh Jul 8, 2026
3e52ffb
feat: 仕切書の TypeScript 型・adapters・バックアップ対象拡張 (Phase C) (#54)
strnh Jul 8, 2026
2d63620
Merge remote-tracking branch 'origin/main' into feature/54-settlements
strnh Jul 8, 2026
5ededc9
fix: PR #56 の Copilot review 指摘に対応
strnh Jul 8, 2026
e685d93
fix: PR #56 の追加レビュー指摘に対応
strnh Jul 8, 2026
41a5a6a
fix: settlement scheduleのIDフィルタを厳密化
strnh Jul 8, 2026
ed272df
fix: PR #56 の未解決レビューに対応
strnh Jul 8, 2026
ba6db01
fix: localの仕切書金額計算を整数化
strnh Jul 8, 2026
644d54d
fix: backup復元時の終了条件を検証
strnh Jul 8, 2026
a0eddc8
fix: 仕切書の部分更新で既存金額を維持
strnh Jul 8, 2026
f1f4503
fix: backup復元時の仕切書条件を検証
strnh Jul 8, 2026
964fa9f
Potential fix for pull request finding
strnh Jul 8, 2026
4b20785
fix: 仕切書の関連ID検証を厳密化
strnh Jul 8, 2026
1d5add9
fix: 仕切書予定同期の再生成境界を修正
strnh Jul 8, 2026
af3bab9
feat: 仕切書の入力UI(一覧・作成/編集・詳細)を追加 (#58)
strnh Jul 8, 2026
60d357f
test: 仕切書予定バックアップ復元の値域検証に回帰テストを追加
strnh Jul 9, 2026
9228f0d
fix: local仕切書の終了条件判定で空文字end_dateを未設定扱いに統一
strnh Jul 9, 2026
f5564f9
fix: 仕切書フォームの未選択時payload正規化とスナップショットクリア
strnh Jul 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions app/Console/Commands/BackupExport.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
use App\Models\CustomerSignature;
use App\Models\Quote;
use App\Models\SenderProfile;
use App\Models\Settlement;
use App\Models\SettlementSchedule;
use App\Services\BackupAudit;
use App\Services\BackupRestorer;
use Illuminate\Console\Command;
Expand All @@ -27,6 +29,8 @@ public function handle(BackupAudit $audit): int
'customers' => Customer::all()->toArray(),
'customer_signatures' => CustomerSignature::all()->toArray(),
'quotes' => Quote::all()->toArray(),
'settlements' => Settlement::all()->toArray(),
'settlement_schedules' => SettlementSchedule::all()->toArray(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);

$output = $this->option('output');
Expand Down
4 changes: 4 additions & 0 deletions app/Http/Controllers/BackupController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
use App\Models\CustomerSignature;
use App\Models\Quote;
use App\Models\SenderProfile;
use App\Models\Settlement;
use App\Models\SettlementSchedule;
use App\Services\BackupRestorer;
use App\Services\BackupStorage;
use Illuminate\Http\JsonResponse;
Expand Down Expand Up @@ -84,6 +86,8 @@ public function download(): JsonResponse
'customers' => Customer::all()->toArray(),
'customer_signatures' => CustomerSignature::all()->toArray(),
'quotes' => Quote::all()->toArray(),
'settlements' => Settlement::all()->toArray(),
'settlement_schedules' => SettlementSchedule::all()->toArray(),
]);
}

Expand Down
131 changes: 131 additions & 0 deletions app/Http/Controllers/SettlementController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
<?php

namespace App\Http\Controllers;

use App\Models\Settlement;
use App\Support\SettlementPricing;
use App\Support\SettlementScheduleGenerator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class SettlementController extends Controller
{
public function index()
{
return Settlement::with('settlementSchedules')
->orderByDesc('start_date')
->orderByDesc('id')
->get();
}

public function store(Request $request)
{
$data = SettlementPricing::apply($this->validated($request));

$settlement = DB::transaction(function () use ($data) {
$settlement = Settlement::create($data);
// interval_count 等の DB default を attributes に反映してから各回を生成する。
$settlement->refresh();
// 新規作成時は過去/未来の区別なく全回を予定データとして持つ。
$settlement->settlementSchedules()->createMany(
SettlementScheduleGenerator::generate($settlement),
);

return $settlement;
});

return response()->json($settlement->load('settlementSchedules'), 201);
}

public function show(Settlement $settlement)
{
return $settlement->load('settlementSchedules');
}

public function update(Request $request, Settlement $settlement)
{
$data = SettlementPricing::apply(array_merge(
$settlement->only(['items', 'tax_rate']),
$this->validated($request),
));

DB::transaction(function () use ($settlement, $data) {
$settlement->update($data);
$settlement->refresh();
// 過去回のスナップショットは不変。基準日(今日)以降の回だけ現在条件で作り直す。
SettlementScheduleGenerator::sync($settlement);
});

return $settlement->fresh()->load('settlementSchedules');
}

public function destroy(Settlement $settlement)
{
$settlement->delete();

return response()->noContent();
}

private function validated(Request $request): array
{
return $request->validate([
// settlement_number は quote_number と同じ扱い(nullable + UNIQUE)。
// 未設定(null)は対象外=番号なし下書きは複数作成可能。
'settlement_number' => [
'nullable', 'string', 'max:100',
Rule::unique('settlements', 'settlement_number')->ignore($request->route('settlement')),
],
'subject' => ['nullable', 'string', 'max:255'],
// status/interval_count/billing_timing/tax_rate は DB 側が NOT NULL + default。
// nullable だと明示的な null が DB エラー(500)になるため、未指定は default に
// 任せつつ null は 422 で弾くために sometimes を使う(値が来た時だけ検証する)。
'status' => ['sometimes', 'in:draft,active,ended'],

// 終了条件は必須: end_date か occurrences_count のいずれか(無期限は不可)。
'start_date' => ['required', 'date'],
'end_date' => ['nullable', 'required_without:occurrences_count', 'date', 'after_or_equal:start_date'],
'occurrences_count' => ['nullable', 'required_without:end_date', 'integer', 'min:1'],
'interval_unit' => ['required', 'in:month,year'],
'interval_count' => ['sometimes', 'integer', 'min:1'],
'billing_day' => ['nullable', 'integer', 'between:1,31'],
'billing_timing' => ['sometimes', 'in:advance,arrears'],

'payment_terms' => ['nullable', 'string', 'max:255'],
'tax_rate' => ['sometimes', 'integer', 'min:0', 'max:100'],
'notes' => ['nullable', 'string'],
Comment thread
Copilot marked this conversation as resolved.

'sender_profile_id' => ['nullable', 'integer'],
'sender_company' => ['nullable', 'string', 'max:255'],
'sender_zip' => ['nullable', 'string', 'max:20'],
'sender_pref' => ['nullable', 'string', 'max:50'],
'sender_city' => ['nullable', 'string', 'max:255'],
'sender_address1' => ['nullable', 'string', 'max:255'],
'sender_address2' => ['nullable', 'string', 'max:255'],
'sender_person' => ['nullable', 'string', 'max:255'],
'sender_tel' => ['nullable', 'string', 'max:50'],
'sender_fax' => ['nullable', 'string', 'max:50'],
'sender_logo_url' => ['nullable', 'string'],

'customer_id' => ['nullable', 'integer'],
'customer_name' => ['nullable', 'string', 'max:255'],
'customer_department' => ['nullable', 'string', 'max:255'],
'customer_person' => ['nullable', 'string', 'max:255'],
'customer_zip' => ['nullable', 'string', 'max:20'],
'customer_pref' => ['nullable', 'string', 'max:50'],
'customer_city' => ['nullable', 'string', 'max:255'],
'customer_address1' => ['nullable', 'string', 'max:255'],
'customer_address2' => ['nullable', 'string', 'max:255'],
'customer_tel' => ['nullable', 'string', 'max:50'],

'items' => ['nullable', 'array'],
'items.*.name' => ['nullable', 'string', 'max:255'],
'items.*.spec' => ['nullable', 'string', 'max:255'],
'items.*.quantity' => ['nullable', 'numeric'],
'items.*.unit' => ['nullable', 'string', 'max:50'],
'items.*.standard_price' => ['nullable', 'numeric'],
'items.*.unit_price' => ['nullable', 'numeric'],
'items.*.total' => ['nullable', 'numeric'],
]);
}
}
31 changes: 31 additions & 0 deletions app/Http/Controllers/SettlementScheduleController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace App\Http\Controllers;

use App\Models\SettlementSchedule;
use Illuminate\Http\Request;

class SettlementScheduleController extends Controller
{
/**
* 各回の請求予定データを取り出す(帳票化はしない。外部が JSON で取得する口)。
* フィルタ: ?settlement_id= / ?from= / ?to=(from/to は billing_date に対する範囲)。
*/
public function index(Request $request)
{
$filters = $request->validate([
'settlement_id' => ['nullable', 'integer'],
'from' => ['nullable', 'date'],
'to' => ['nullable', 'date', 'after_or_equal:from'],
]);

return SettlementSchedule::query()
->when(isset($filters['settlement_id']), fn ($query) => $query->where('settlement_id', $filters['settlement_id']))
->when($filters['from'] ?? null, fn ($query, $from) => $query->whereDate('billing_date', '>=', $from))
->when($filters['to'] ?? null, fn ($query, $to) => $query->whereDate('billing_date', '<=', $to))
->orderBy('billing_date')
->orderBy('settlement_id')
->orderBy('sequence_no')
->get();
}
}
29 changes: 29 additions & 0 deletions app/Models/Settlement.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Settlement extends Model
{
protected $guarded = ['id'];

protected $casts = [
'items' => 'array',
'start_date' => 'date:Y-m-d',
'end_date' => 'date:Y-m-d',
'occurrences_count' => 'integer',
'interval_count' => 'integer',
'billing_day' => 'integer',
'tax_rate' => 'integer',
'unit_subtotal' => 'integer',
'unit_tax_amount' => 'integer',
'unit_total_amount' => 'integer',
];

public function settlementSchedules(): HasMany
{
return $this->hasMany(SettlementSchedule::class)->orderBy('sequence_no');
}
Comment thread
Copilot marked this conversation as resolved.
}
28 changes: 28 additions & 0 deletions app/Models/SettlementSchedule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class SettlementSchedule extends Model
{
protected $guarded = ['id'];

protected $casts = [
'items' => 'array',
'sequence_no' => 'integer',
'period_start' => 'date:Y-m-d',
'period_end' => 'date:Y-m-d',
'billing_date' => 'date:Y-m-d',
'due_date' => 'date:Y-m-d',
'subtotal' => 'integer',
'tax_amount' => 'integer',
'total_amount' => 'integer',
];

public function settlement(): BelongsTo
{
return $this->belongsTo(Settlement::class);
}
}
90 changes: 85 additions & 5 deletions app/Services/BackupRestorer.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@
use Illuminate\Database\QueryException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class BackupRestorer
{
/** エクスポート形式のバージョン。2 で customers から customer_signatures を分離した。 */
public const VERSION = 2;
/**
* エクスポート形式のバージョン。
* 2 で customers から customer_signatures を分離、3 で settlements / settlement_schedules を追加した。
*/
public const VERSION = 3;

/** 復元を受け付けるバージョン。1 は customers[].customer_signature を含む旧形式。 */
public const SUPPORTED_VERSIONS = [1, 2];
public const SUPPORTED_VERSIONS = [1, 2, 3];

/**
* @return array{inserted: int, skipped: int, updated: int, errors: array<int, string>}
Expand Down Expand Up @@ -44,13 +48,30 @@ public function restore(array $data, string $mode): array
return $row;
});

$this->restoreRows('quotes', $data['quotes'] ?? [], $mode, $summary, function (array $row): array {
$encodeItems = function (array $row): array {
if (isset($row['items']) && is_array($row['items'])) {
$row['items'] = json_encode($row['items'], JSON_UNESCAPED_UNICODE);
}

return $row;
});
};

$this->restoreRows('quotes', $data['quotes'] ?? [], $mode, $summary, $encodeItems);

$restoredSettlementIds = $this->restoreRows('settlements', $data['settlements'] ?? [], $mode, $summary, $encodeItems);
// JSON decode で int/string どちらにもなり得るため、文字列キーの set で照合する。
$restoredSettlementIdSet = array_fill_keys(array_map('strval', $restoredSettlementIds), true);

$scheduleRows = [];
foreach ($data['settlement_schedules'] ?? [] as $row) {
if (isset($restoredSettlementIdSet[(string) ($row['settlement_id'] ?? '')])) {
$scheduleRows[] = $row;
} else {
// skip された親や存在しない親の予定を、同じIDの別仕切書へ紐付けない。
$summary['skipped']++;
}
}
$this->restoreRows('settlement_schedules', $scheduleRows, $mode, $summary, $encodeItems);
});

return $summary;
Expand All @@ -67,6 +88,15 @@ private function validateRows(array $data): void
'customers' => ['customer_name'],
'customer_signatures' => ['customer_id', 'signature'],
'quotes' => [],
'settlements' => ['start_date', 'interval_unit'],
'settlement_schedules' => ['settlement_id', 'sequence_no', 'period_start', 'period_end', 'billing_date'],
Comment thread
strnh marked this conversation as resolved.
];
$nonNullableDefaultColumns = [
'settlements' => [
'status', 'interval_count', 'billing_timing', 'tax_rate',
'unit_subtotal', 'unit_tax_amount', 'unit_total_amount',
],
'settlement_schedules' => ['subtotal', 'tax_amount', 'total_amount'],
];

foreach ($requiredColumns as $table => $columns) {
Expand Down Expand Up @@ -101,6 +131,56 @@ private function validateRows(array $data): void
]);
}
}

// default 付きカラムは省略を許すが、明示的な null / 非スカラ値は DB 例外になるため拒否する。
foreach ($nonNullableDefaultColumns[$table] ?? [] as $column) {
if (array_key_exists($column, $row)
&& (! is_scalar($row[$column]) || $row[$column] === '')) {
throw ValidationException::withMessages([
'file' => ["{$table}.{$index} の {$column} が不正です。"],
]);
}
}

if ($table === 'settlements') {
$validator = Validator::make($row, [
'status' => ['sometimes', 'in:draft,active,ended'],
'start_date' => ['required', 'date'],
'end_date' => ['nullable', 'required_without:occurrences_count', 'date', 'after_or_equal:start_date'],
'occurrences_count' => ['nullable', 'required_without:end_date', 'integer', 'min:1'],
'interval_unit' => ['required', 'in:month,year'],
'interval_count' => ['sometimes', 'integer', 'min:1'],
'billing_day' => ['nullable', 'integer', 'between:1,31'],
'billing_timing' => ['sometimes', 'in:advance,arrears'],
'tax_rate' => ['sometimes', 'integer', 'between:0,100'],
'items' => ['nullable', 'array'],
]);
if ($validator->fails()) {
throw ValidationException::withMessages([
'file' => ["{$table}.{$index} の値が不正です: {$validator->errors()->first()}"],
]);
}
}

if ($table === 'settlement_schedules') {
$validator = Validator::make($row, [
'settlement_id' => ['required', 'integer', 'min:1'],
'sequence_no' => ['required', 'integer', 'min:1'],
'period_start' => ['required', 'date'],
'period_end' => ['required', 'date', 'after_or_equal:period_start'],
'billing_date' => ['required', 'date'],
'due_date' => ['nullable', 'date'],
'subtotal' => ['sometimes', 'integer'],
'tax_amount' => ['sometimes', 'integer'],
'total_amount' => ['sometimes', 'integer'],
'items' => ['nullable', 'array'],
]);
if ($validator->fails()) {
throw ValidationException::withMessages([
'file' => ["{$table}.{$index} の値が不正です: {$validator->errors()->first()}"],
]);
}
}
Comment thread
Copilot marked this conversation as resolved.
}
}
}
Expand Down
Loading