Fight Pro - Sistema de Registro de Lutas

Fight PRO

Sistema de Registros Esportivos

Visitante

Total Lutadores

0

Eventos Ativos

0

Lutas Registradas

0

Staff Ativo

0

Próximos Eventos e Lutas

Nenhum evento cadastrado

Últimas Lutas Realizadas

Nenhuma luta realizada

Gerenciamento de Lutadores

Lutador Modalidade Divisão Categoria Cartel Ações
Nenhum lutador cadastrado

Gerenciamento de Eventos

Nenhum evento cadastrado

Registro de Lutas

Evento Lutadores Modalidade Categoria Resultado Ações
Nenhuma luta registrada

Organizações

Nenhuma organização cadastrada

Staff T��cnico e Oficiais

Árbitros

0

Ju��zes

0

Promotores

0

Médicos

0

Cronometristas

0

Nome Funç����o Experiência Contato Ações
Nenhum membro cadastrado

Rankings por Organização

Posição Lutador Cartel Pontuação Última Luta
Selecione os filtros para visualizar o ranking

Painel do Administrador

Configurações do Dashboard

Gerenciar Editores

Nenhum editor cadastrado

Sincronização Google Sheets

Cole a URL do seu Web App do Google Apps Script

Ativar sincronização automática com Google Sheets

Status: Desconectado

Estat��sticas Gerais

Total de Usuários: 1
Eventos Este Mês: 0
Lutas Este M����s: 0
Último Backup: Nunca

Ações de Manutenção

Código do Google Apps Script

Instruções: 1. Copie o código abaixo | 2. Acesse Google Apps Script | 3. Crie um novo projeto | 4. Cole o código | 5. Implante como Web App | 6. Cole a URL gerada no campo acima

// Google Apps Script para Fight Manager Pro
// Este script sincroniza dados do sistema com Google Sheets em tempo real

const SPREADSHEET_ID = 'SEU_ID_DA_PLANILHA_AQUI'; // Cole o ID da sua planilha

function doGet(e) {
  return ContentService.createTextOutput(JSON.stringify({ status: 'ok' }))
    .setMimeType(ContentService.MimeType.JSON);
}

function doPost(e) {
  try {
    const data = JSON.parse(e.postData.contents);
    const action = data.action;
    
    switch(action) {
      case 'sync_all':
        return syncAllData(data.payload);
      case 'add_fighter':
        return addFighter(data.payload);
      case 'add_event':
        return addEvent(data.payload);
      case 'add_fight':
        return addFight(data.payload);
      case 'add_organization':
        return addOrganization(data.payload);
      case 'add_staff':
        return addStaff(data.payload);
      case 'test_connection':
        return testConnection();
      default:
        return createResponse(false, 'Ação desconhecida');
    }
  } catch(error) {
    return createResponse(false, 'Erro: ' + error.message);
  }
}

function testConnection() {
  return createResponse(true, 'Conexão estabelecida com sucesso!');
}

function syncAllData(data) {
  try {
    const ss = SpreadsheetApp.openById(SPREADSHEET_ID);
    
    // Sincronizar lutadores
    if (data.fighters) {
      syncSheet(ss, 'Lutadores', data.fighters, [
        'ID', 'Foto URL', 'Nome', 'Apelido', 'Nascimento', 'Nacionalidade', 
        'Cidade Natal', 'Residência', 'Equipe', 'Gênero', 'Divisão',
        'Peso', 'Modalidade', 'Vitórias', 'Derrotas', 'Empates', 'Títulos'
      ]);
    }
    
    // Sincronizar eventos
    if (data.events) {
      syncSheet(ss, 'Eventos', data.events, [
        'ID', 'Nome', 'Data', 'Local', 'Organização', 'Promotor',
        'Matchmaker', 'Inspetor', 'Médico', 'Descrição'
      ]);
    }
    
    // Sincronizar lutas
    if (data.fights) {
      syncSheet(ss, 'Lutas', data.fights, [
        'ID', 'ID Evento', 'ID Lutador 1', 'ID Lutador 2', 'Modalidade',
        'Divisão', 'Peso', 'Rounds', 'Status', 'Título', 
        'ID Árbitro', 'ID Juiz 1', 'ID Juiz 2', 'ID Juiz 3', 
        'ID Supervisor', 'ID Médico',
        'Resultado', 'Tipo Resultado', 'Round Final', 'Tempo Final', 
        'Observações', 'Data'
      ]);
    }
    
    // Sincronizar editores
    if (data.editors) {
      syncSheet(ss, 'Editores', data.editors, [
        'ID', 'Nome', 'Email', 'Senha', 'ID Organização', 
        'Nome Organização', 'Data Cadastro'
      ]);
    }
    
    // Sincronizar organizações
    if (data.organizations) {
      syncSheet(ss, 'Organizações', data.organizations, [
        'ID', 'Nome', 'Sigla', 'País', 'Fundação', 'Descrição'
      ]);
    }
    
    // Sincronizar staff
    if (data.staff) {
      syncSheet(ss, 'Staff', data.staff, [
        'ID', 'Nome', 'Função', 'Email', 'Telefone',
        'Experiência', 'Licença', 'Observações'
      ]);
    }
    
    return createResponse(true, 'Dados sincronizados com sucesso!');
  } catch(error) {
    return createResponse(false, 'Erro ao sincronizar: ' + error.message);
  }
}

function syncSheet(ss, sheetName, data, headers) {
  let sheet = ss.getSheetByName(sheetName);
  
  // Criar aba se não existir
  if (!sheet) {
    sheet = ss.insertSheet(sheetName);
    sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
    sheet.getRange(1, 1, 1, headers.length).setFontWeight('bold')
      .setBackground('#9333ea').setFontColor('#ffffff');
    sheet.setFrozenRows(1);
  }
  
  // Limpar dados existentes (exceto cabeçalho)
  if (sheet.getLastRow() > 1) {
    sheet.getRange(2, 1, sheet.getLastRow() - 1, headers.length).clear();
  }
  
  // Inserir novos dados
  if (data.length > 0) {
    const rows = data.map(item => {
      return headers.map(header => {
        const key = headerToKey(header);
        let value = item[key] || '';
        
        // Truncar valores muito longos (Base64 de fotos)
        if (typeof value === 'string' && value.length > 50000) {
          value = value.substring(0, 50000) + '... [truncado]';
        }
        
        return value;
      });
    });
    
    sheet.getRange(2, 1, rows.length, headers.length).setValues(rows);
  }
  
  // Formatar
  sheet.autoResizeColumns(1, headers.length);
  
  // Adicionar filtros
  if (sheet.getLastRow() > 0) {
    const range = sheet.getRange(1, 1, sheet.getLastRow(), headers.length);
    range.createFilter();
  }
}

function addFighter(fighter) {
  const ss = SpreadsheetApp.openById(SPREADSHEET_ID);
  let sheet = ss.getSheetByName('Lutadores');
  
  if (!sheet) {
    sheet = ss.insertSheet('Lutadores');
    const headers = ['ID', 'Nome', 'Apelido', 'Nascimento', 'Nacionalidade', 
                     'Cidade Natal', 'Residência', 'Equipe', 'Gênero', 'Divisão',
                     'Peso', 'Modalidade', 'Vitórias', 'Derrotas', 'Empates', 'Títulos'];
    sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
    sheet.getRange(1, 1, 1, headers.length).setFontWeight('bold')
      .setBackground('#9333ea').setFontColor('#ffffff');
  }
  
  const row = [
    fighter.id, fighter.name, fighter.nickname, fighter.birthdate,
    fighter.nationality, fighter.hometown, fighter.residence, fighter.team,
    fighter.gender, fighter.division, fighter.weight, fighter.modality,
    fighter.wins, fighter.losses, fighter.draws, fighter.titles
  ];
  
  sheet.appendRow(row);
  return createResponse(true, 'Lutador adicionado à planilha');
}

function addEvent(event) {
  const ss = SpreadsheetApp.openById(SPREADSHEET_ID);
  let sheet = ss.getSheetByName('Eventos');
  
  if (!sheet) {
    sheet = ss.insertSheet('Eventos');
    const headers = ['ID', 'Nome', 'Data', 'Local', 'Organização', 'Promotor',
                     'Matchmaker', 'Inspetor', 'Médico', 'Descrição'];
    sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
    sheet.getRange(1, 1, 1, headers.length).setFontWeight('bold')
      .setBackground('#9333ea').setFontColor('#ffffff');
  }
  
  const row = [
    event.id, event.name, event.date, event.location, event.organization,
    event.promoter, event.matchmaker, event.inspector, event.doctor, event.description
  ];
  
  sheet.appendRow(row);
  return createResponse(true, 'Evento adicionado à planilha');
}

function addFight(fight) {
  const ss = SpreadsheetApp.openById(SPREADSHEET_ID);
  let sheet = ss.getSheetByName('Lutas');
  
  if (!sheet) {
    sheet = ss.insertSheet('Lutas');
    const headers = ['ID', 'ID Evento', 'ID Lutador 1', 'ID Lutador 2', 'Modalidade',
                     'Divisão', 'Peso', 'Título', 'Resultado', 'Observações', 'Data'];
    sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
    sheet.getRange(1, 1, 1, headers.length).setFontWeight('bold')
      .setBackground('#9333ea').setFontColor('#ffffff');
  }
  
  const row = [
    fight.id, fight.eventId, fight.fighter1Id, fight.fighter2Id,
    fight.modality, fight.division, fight.weight, fight.title,
    fight.result, fight.notes, fight.date
  ];
  
  sheet.appendRow(row);
  return createResponse(true, 'Luta adicionada à planilha');
}

function addOrganization(org) {
  const ss = SpreadsheetApp.openById(SPREADSHEET_ID);
  let sheet = ss.getSheetByName('Organizações');
  
  if (!sheet) {
    sheet = ss.insertSheet('Organizações');
    const headers = ['ID', 'Nome', 'Sigla', 'País', 'Fundação', 'Descrição'];
    sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
    sheet.getRange(1, 1, 1, headers.length).setFontWeight('bold')
      .setBackground('#9333ea').setFontColor('#ffffff');
  }
  
  const row = [org.id, org.name, org.acronym, org.country, org.founded, org.description];
  sheet.appendRow(row);
  return createResponse(true, 'Organização adicionada à planilha');
}

function addStaff(member) {
  const ss = SpreadsheetApp.openById(SPREADSHEET_ID);
  let sheet = ss.getSheetByName('Staff');
  
  if (!sheet) {
    sheet = ss.insertSheet('Staff');
    const headers = ['ID', 'Nome', 'Função', 'Email', 'Telefone',
                     'Experiência', 'Licença', 'Observações'];
    sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
    sheet.getRange(1, 1, 1, headers.length).setFontWeight('bold')
      .setBackground('#9333ea').setFontColor('#ffffff');
  }
  
  const row = [
    member.id, member.name, member.role, member.email, member.phone,
    member.experience, member.license, member.notes
  ];
  
  sheet.appendRow(row);
  return createResponse(true, 'Membro do staff adicionado à planilha');
}

function headerToKey(header) {
  const mapping = {
    'ID': 'id',
    'Foto URL': 'photo',
    'Nome': 'name',
    'Apelido': 'nickname',
    'Nascimento': 'birthdate',
    'Nacionalidade': 'nationality',
    'Cidade Natal': 'hometown',
    'Residência': 'residence',
    'Equipe': 'team',
    'Gênero': 'gender',
    'Divisão': 'division',
    'Peso': 'weight',
    'Modalidade': 'modality',
    'Vitórias': 'wins',
    'Derrotas': 'losses',
    'Empates': 'draws',
    'Títulos': 'titles',
    'Data': 'date',
    'Local': 'location',
    'Organização': 'organization',
    'Promotor': 'promoter',
    'Matchmaker': 'matchmaker',
    'Inspetor': 'inspector',
    'Médico': 'doctor',
    'Descrição': 'description',
    'ID Evento': 'eventId',
    'ID Lutador 1': 'fighter1Id',
    'ID Lutador 2': 'fighter2Id',
    'Rounds': 'rounds',
    'Status': 'status',
    'Título': 'title',
    'ID Árbitro': 'refereeId',
    'ID Juiz 1': 'judge1Id',
    'ID Juiz 2': 'judge2Id',
    'ID Juiz 3': 'judge3Id',
    'ID Supervisor': 'supervisorId',
    'ID Médico': 'doctorId',
    'Resultado': 'result',
    'Tipo Resultado': 'resultType',
    'Round Final': 'finishRound',
    'Tempo Final': 'finishTime',
    'Observações': 'notes',
    'Sigla': 'acronym',
    'País': 'country',
    'Fundação': 'founded',
    'Função': 'role',
    'Email': 'email',
    'Senha': 'password',
    'Telefone': 'phone',
    'Experiência': 'experience',
    'Licença': 'license',
    'ID Organização': 'organizationId',
    'Nome Organização': 'organizationName',
    'Data Cadastro': 'addedAt'
  };
  
  return mapping[header] || header.toLowerCase();
}

function createResponse(success, message) {
  return ContentService.createTextOutput(JSON.stringify({
    success: success,
    message: message,
    timestamp: new Date().toISOString()
  })).setMimeType(ContentService.MimeType.JSON);
}

Importante: Não esqueça de substituir SEU_ID_DA_PLANILHA_AQUI pelo ID da sua planilha do Google Sheets!