id(); $table->foreignId('tenant_id')->constrained('tenants'); $table->uuid('client_key'); $table->string('code', 40); $table->string('name', 180); $table->string('tax_number', 40)->nullable(); $table->text('address')->nullable(); $table->string('email', 254)->nullable(); $table->boolean('active')->default(true); $table->unsignedInteger('version')->default(1); $table->foreignId('created_by')->constrained('users'); $table->string('creation_hash', 64); $table->timestamps(); $table->unique(['tenant_id', 'client_key']); $table->unique(['tenant_id', 'code']); $table->unique(['id', 'tenant_id']); }); if (DB::getDriverName() === 'pgsql') { DB::unprepared("CREATE FUNCTION sgc_preserve_business_client() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Preservar identidade do cliente'; END IF; IF ROW(NEW.tenant_id,NEW.client_key,NEW.created_by,NEW.creation_hash,NEW.created_at) IS DISTINCT FROM ROW(OLD.tenant_id,OLD.client_key,OLD.created_by,OLD.creation_hash,OLD.created_at) OR NEW.version <> OLD.version + 1 THEN RAISE EXCEPTION 'Preservar identidade e versao do cliente'; END IF; RETURN NEW; END \$\$; CREATE TRIGGER sgc_preserve_business_client BEFORE UPDATE OR DELETE ON business_clients FOR EACH ROW EXECUTE FUNCTION sgc_preserve_business_client();"); } elseif (DB::getDriverName() === 'sqlite') { DB::unprepared("CREATE TRIGGER sgc_preserve_business_client_update BEFORE UPDATE ON business_clients WHEN NEW.tenant_id IS NOT OLD.tenant_id OR NEW.client_key IS NOT OLD.client_key OR NEW.created_by IS NOT OLD.created_by OR NEW.creation_hash IS NOT OLD.creation_hash OR NEW.created_at IS NOT OLD.created_at OR NEW.version <> OLD.version + 1 BEGIN SELECT RAISE(ABORT, 'Preservar identidade e versao do cliente'); END; CREATE TRIGGER sgc_preserve_business_client_delete BEFORE DELETE ON business_clients BEGIN SELECT RAISE(ABORT, 'Preservar identidade do cliente'); END;"); } } public function down(): void { throw new LogicException('Preservar clientes e identidades congeladas nos processos.'); } };