2026_11_11_190000_start_daily_backflow.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. use App\Support\BackflowPeriod;
  3. use Illuminate\Database\Migrations\Migration;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Schema;
  7. return new class extends Migration {
  8. public function up(): void
  9. {
  10. if (!Schema::hasColumn('backflow', 'daily_date')) {
  11. Schema::table('backflow', function (Blueprint $table) {
  12. // Keep legacy monthly rows and enforce one row per member for each new daily period.
  13. $table->string('daily_date', 10)->nullable()->virtualAs('CASE WHEN LENGTH(date) = 10 THEN date END');
  14. });
  15. }
  16. if (!Schema::hasIndex('backflow', 'backflow_member_daily_unique')) {
  17. Schema::table('backflow', function (Blueprint $table) {
  18. $table->unique(['member_id', 'daily_date'], 'backflow_member_daily_unique');
  19. });
  20. }
  21. if (!Schema::hasIndex('backflow', 'backflow_status_date_index')) {
  22. Schema::table('backflow', function (Blueprint $table) {
  23. $table->index(['status', 'date'], 'backflow_status_date_index');
  24. });
  25. }
  26. $now = now(BackflowPeriod::TIMEZONE);
  27. DB::table('share_system_state')->insertOrIgnore([
  28. 'key' => BackflowPeriod::DAILY_FROM_KEY,
  29. 'value' => $now->copy()->addDay()->toDateString(),
  30. 'created_at' => $now,
  31. 'updated_at' => $now,
  32. ]);
  33. }
  34. public function down(): void
  35. {
  36. if (DB::table('backflow')->whereNotNull('daily_date')->exists()) {
  37. throw new RuntimeException('已有日回水记录,不能自动恢复月回水');
  38. }
  39. DB::table('share_system_state')->where('key', BackflowPeriod::DAILY_FROM_KEY)->delete();
  40. Schema::table('backflow', function (Blueprint $table) {
  41. $table->dropIndex('backflow_status_date_index');
  42. $table->dropUnique('backflow_member_daily_unique');
  43. $table->dropColumn('daily_date');
  44. });
  45. }
  46. };