console.log( 'Code is Poetry' ); [
'name' => 'Leads GoSeller',
'singular_name' => 'Lead',
'menu_name' => 'Leads GoSeller',
'all_items' => 'Todos os Leads',
'edit_item' => 'Ver Lead',
'view_item' => 'Visualizar Lead',
'search_items' => 'Buscar Leads',
'not_found' => 'Nenhum lead encontrado',
'not_found_in_trash' => 'Nenhum lead na lixeira',
],
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'menu_icon' => 'dashicons-businessperson',
'menu_position' => 25,
'supports' => ['title'],
'capability_type' => 'post',
'has_archive' => false,
'exclude_from_search'=> true,
'publicly_queryable' => false,
]);
}
add_action('init', 'goseller_register_leads_cpt');
// ═══════════════════════════════════════════════════════
// 2. ENDPOINT REST: /wp-json/goseller/v1/leads
// ═══════════════════════════════════════════════════════
function goseller_register_rest_route() {
register_rest_route('goseller/v1', '/leads', [
'methods' => 'POST',
'callback' => 'goseller_handle_lead_submission',
'permission_callback' => '__return_true', // endpoint público
]);
}
add_action('rest_api_init', 'goseller_register_rest_route');
// ═══════════════════════════════════════════════════════
// 3. HANDLER DO FORMULÁRIO
// ═══════════════════════════════════════════════════════
function goseller_handle_lead_submission($request) {
$params = $request->get_json_params();
if (empty($params)) $params = $request->get_params();
// HONEYPOT — se bot preencheu o campo "website", finge sucesso e descarta
if (!empty($params['website'])) {
return rest_ensure_response(['success' => true]);
}
// Validação mínima
$nome = sanitize_text_field($params['nome'] ?? '');
$whatsapp = sanitize_text_field($params['whatsapp'] ?? '');
$email = sanitize_email($params['email'] ?? '');
if (empty($nome) || empty($whatsapp) || empty($email)) {
return new WP_Error('missing_fields', 'Preencha nome, WhatsApp e e-mail.', ['status' => 400]);
}
if (!is_email($email)) {
return new WP_Error('invalid_email', 'E-mail inválido.', ['status' => 400]);
}
// Cria o post do lead
$post_id = wp_insert_post([
'post_type' => 'goseller_lead',
'post_status' => 'publish',
'post_title' => $nome . ' — ' . $email,
]);
if (is_wp_error($post_id)) {
return new WP_Error('creation_failed', 'Erro ao salvar o lead.', ['status' => 500]);
}
// Salva os campos
$fields = [
'nome', 'whatsapp', 'email',
'segmento', 'faturamento', 'budget',
'authority', 'necessity', 'contexto', 'time',
'aceite_marketing'
];
foreach ($fields as $field) {
if (isset($params[$field])) {
$value = is_array($params[$field])
? implode(', ', array_map('sanitize_text_field', $params[$field]))
: sanitize_text_field($params[$field]);
update_post_meta($post_id, '_goseller_' . $field, $value);
}
}
update_post_meta($post_id, '_goseller_ip', sanitize_text_field($_SERVER['REMOTE_ADDR'] ?? ''));
update_post_meta($post_id, '_goseller_user_agent', sanitize_text_field($_SERVER['HTTP_USER_AGENT'] ?? ''));
update_post_meta($post_id, '_goseller_submitted_at', current_time('mysql'));
// Notifica por e-mail
goseller_notify_admin($post_id, $params);
return rest_ensure_response([
'success' => true,
'message' => 'Lead recebido.',
'id' => $post_id,
]);
}
// ═══════════════════════════════════════════════════════
// 4. E-MAIL DE NOTIFICAÇÃO PRO ADMIN
// ═══════════════════════════════════════════════════════
function goseller_notify_admin($post_id, $params) {
$to = get_option('admin_email');
$nome = sanitize_text_field($params['nome'] ?? '');
$subject = '🦈 Novo Lead GoSeller: ' . $nome;
$labels = goseller_get_labels();
$budget_label = $labels['budget'][$params['budget'] ?? ''] ?? ($params['budget'] ?? '—');
$time_label = $labels['time'][$params['time'] ?? ''] ?? ($params['time'] ?? '—');
$auth_label = $labels['authority'][$params['authority'] ?? ''] ?? ($params['authority'] ?? '—');
$necessities = $params['necessity'] ?? [];
if (is_array($necessities)) {
$necessities = array_map(function($n) use ($labels){ return $labels['necessity'][$n] ?? $n; }, $necessities);
$necessities = implode(', ', $necessities);
}
$message = "Novo lead recebido pelo formulário de diagnóstico:\n\n";
$message .= "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
$message .= "CONTATO\n";
$message .= "Nome: " . $nome . "\n";
$message .= "WhatsApp: " . ($params['whatsapp'] ?? '-') . "\n";
$message .= "E-mail: " . ($params['email'] ?? '-') . "\n\n";
$message .= "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
$message .= "QUALIFICAÇÃO (BANT)\n";
$message .= "Segmento: " . ($params['segmento'] ?? '-') . "\n";
$message .= "Faturamento: " . ($params['faturamento'] ?? '-') . "\n";
$message .= "Verba disponível: " . $budget_label . "\n";
$message .= "Autoridade: " . $auth_label . "\n";
$message .= "Urgência: " . $time_label . "\n\n";
$message .= "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
$message .= "NECESSIDADES\n";
$message .= $necessities . "\n\n";
if (!empty($params['contexto'])) {
$message .= "CONTEXTO\n";
$message .= sanitize_textarea_field($params['contexto']) . "\n\n";
}
$message .= "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
$message .= "Ver no painel: " . admin_url('post.php?post=' . $post_id . '&action=edit') . "\n";
wp_mail($to, $subject, $message);
}
// ═══════════════════════════════════════════════════════
// 5. LABELS HUMANIZADOS
// ═══════════════════════════════════════════════════════
function goseller_get_labels() {
return [
'budget' => [
'ate1500' => 'Até R$ 1.500',
'1500_3000' => 'R$ 1.500 – R$ 3.000',
'3000_6000' => 'R$ 3.000 – R$ 5.000',
'acima6000' => 'Acima de R$ 5.000',
],
'time' => [
'agora' => '🔥 Urgente',
'1mes' => '⏰ Em 1 mês',
'3meses' => '📅 Em 3 meses',
'indefinido' => '❓ Indefinido',
],
'authority' => [
'sim' => 'Decisor único',
'socio' => 'Decide com sócio',
'conjuge' => 'Decide com cônjuge',
'nao' => 'Não é o decisor',
],
'necessity' => [
'clientes' => 'Poucos clientes novos',
'retencao' => 'Falta de retenção',
'caixa' => 'Caixa irregular',
'trafego' => 'Tráfego sem retorno',
'concorrencia' => 'Concorrência crescendo',
],
];
}
// ═══════════════════════════════════════════════════════
// 6. COLUNAS PERSONALIZADAS NA LISTA DO ADMIN
// ═══════════════════════════════════════════════════════
function goseller_leads_columns($columns) {
return [
'cb' => $columns['cb'],
'title' => 'Lead',
'whatsapp' => 'WhatsApp',
'segmento' => 'Segmento',
'budget' => 'Verba/mês',
'time' => 'Urgência',
'authority' => 'Decisor?',
'date' => 'Recebido em',
];
}
add_filter('manage_goseller_lead_posts_columns', 'goseller_leads_columns');
function goseller_leads_column_content($column, $post_id) {
$labels = goseller_get_labels();
$value = get_post_meta($post_id, '_goseller_' . $column, true);
if (isset($labels[$column][$value])) {
echo esc_html($labels[$column][$value]);
} else {
echo esc_html($value ?: '—');
}
}
add_action('manage_goseller_lead_posts_custom_column', 'goseller_leads_column_content', 10, 2);
// Ordenação por data decrescente por padrão
function goseller_leads_default_sort($query) {
if (!is_admin() || !$query->is_main_query()) return;
if ($query->get('post_type') === 'goseller_lead') {
$query->set('orderby', 'date');
$query->set('order', 'DESC');
}
}
add_action('pre_get_posts', 'goseller_leads_default_sort');
// ═══════════════════════════════════════════════════════
// 7. DETALHES DO LEAD (METABOX)
// ═══════════════════════════════════════════════════════
function goseller_leads_meta_box() {
add_meta_box(
'goseller_lead_details',
'Detalhes do Lead',
'goseller_lead_details_callback',
'goseller_lead',
'normal',
'high'
);
// Remove o editor padrão
remove_post_type_support('goseller_lead', 'editor');
}
add_action('add_meta_boxes', 'goseller_leads_meta_box');
function goseller_lead_details_callback($post) {
$labels = goseller_get_labels();
$map = [
'nome' => ['Nome', null],
'whatsapp' => ['WhatsApp', null],
'email' => ['E-mail', null],
'segmento' => ['Segmento', null],
'faturamento' => ['Faturamento mensal',null],
'budget' => ['Verba disponível', 'budget'],
'authority' => ['Autoridade', 'authority'],
'necessity' => ['Necessidades', null],
'contexto' => ['Contexto informado',null],
'time' => ['Urgência', 'time'],
'aceite_marketing' => ['Aceite marketing', null],
'ip' => ['IP', null],
'submitted_at' => ['Recebido em', null],
];
echo '';
echo ' ';
foreach ($map as $key => $meta) {
$label = $meta[0];
$type = $meta[1];
$value = get_post_meta($post->ID, '_goseller_' . $key, true);
$display = $value;
if ($type && isset($labels[$type][$value])) $display = $labels[$type][$value];
if ($key === 'necessity' && $value) {
$parts = array_map('trim', explode(',', $value));
$parts = array_map(function($p) use ($labels){ return $labels['necessity'][$p] ?? $p; }, $parts);
$display = implode(', ', $parts);
}
if ($key === 'whatsapp' && $value) {
$clean = preg_replace('/\D/', '', $value);
$display = '' . esc_html($value) . ' ↗';
}
if ($key === 'email' && $value) {
$display = '' . esc_html($value) . '';
}
echo '';
echo '' . esc_html($label) . ' ';
echo '' . ($display ?: '—') . ' ';
echo ' ';
}
echo '
';
}
// ═══════════════════════════════════════════════════════
// 8. EXPORTAR CSV
// ═══════════════════════════════════════════════════════
function goseller_export_leads_csv() {
if (!isset($_GET['goseller_export'])) return;
if (!current_user_can('manage_options')) wp_die('Sem permissão.');
if (!wp_verify_nonce($_GET['_wpnonce'] ?? '', 'goseller_export')) wp_die('Nonce inválido.');
$leads = get_posts(['post_type' => 'goseller_lead', 'numberposts' => -1, 'orderby' => 'date', 'order' => 'DESC']);
$labels = goseller_get_labels();
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=leads-goseller-' . date('Y-m-d') . '.csv');
$output = fopen('php://output', 'w');
fputs($output, "\xEF\xBB\xBF"); // BOM pro Excel entender UTF-8
fputcsv($output, [
'Data', 'Nome', 'WhatsApp', 'E-mail', 'Segmento', 'Faturamento',
'Verba', 'Autoridade', 'Necessidades', 'Contexto', 'Urgência', 'IP'
]);
foreach ($leads as $lead) {
$get = function($k) use ($lead) { return get_post_meta($lead->ID, '_goseller_' . $k, true); };
$budget_v = $get('budget');
$time_v = $get('time');
$auth_v = $get('authority');
$necessity_v = $get('necessity');
fputcsv($output, [
$get('submitted_at'),
$get('nome'),
$get('whatsapp'),
$get('email'),
$get('segmento'),
$get('faturamento'),
$labels['budget'][$budget_v] ?? $budget_v,
$labels['authority'][$auth_v] ?? $auth_v,
$necessity_v,
$get('contexto'),
$labels['time'][$time_v] ?? $time_v,
$get('ip'),
]);
}
fclose($output);
exit;
}
add_action('admin_init', 'goseller_export_leads_csv');
// Botão de exportar na listagem
function goseller_leads_export_button($which) {
$screen = get_current_screen();
if (!$screen || $screen->post_type !== 'goseller_lead') return;
if ($which !== 'top') return;
$url = wp_nonce_url(admin_url('edit.php?post_type=goseller_lead&goseller_export=1'), 'goseller_export');
echo '';
}
add_action('manage_posts_extra_tablenav', 'goseller_leads_export_button');
// ═══════════════════════════════════════════════════════
// 9. DASHBOARD WIDGET — resumo na home do admin
// ═══════════════════════════════════════════════════════
function goseller_dashboard_widget() {
wp_add_dashboard_widget('goseller_leads_summary', '🦈 Leads GoSeller — últimos 7 dias', 'goseller_dashboard_widget_callback');
}
add_action('wp_dashboard_setup', 'goseller_dashboard_widget');
function goseller_dashboard_widget_callback() {
$args = [
'post_type' => 'goseller_lead',
'posts_per_page' => 5,
'date_query' => [['after' => '7 days ago']],
];
$q = new WP_Query($args);
$total_week = $q->found_posts;
$total_all = wp_count_posts('goseller_lead')->publish;
echo '' . $total_week . ' lead(s) nos últimos 7 dias · ' . $total_all . ' no total
';
if ($q->have_posts()) {
echo '';
while ($q->have_posts()) { $q->the_post();
$whatsapp = get_post_meta(get_the_ID(), '_goseller_whatsapp', true);
$segmento = get_post_meta(get_the_ID(), '_goseller_segmento', true);
echo '- ';
echo '' . get_the_title() . '';
if ($segmento) echo ' · ' . esc_html($segmento) . '';
echo '
' . get_the_date('d/m/Y H:i') . ' · ' . esc_html($whatsapp) . '';
echo ' ';
}
echo '
';
echo '';
} else {
echo 'Nenhum lead nos últimos 7 dias.
';
}
wp_reset_postdata();
}