aboutsummaryrefslogtreecommitdiff
path: root/web/src/pages/NewTicketPage.tsx
blob: d716f1ec8615bb3bc9d4fb868a5566c2db94d578 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/**
 * NewTicketPage.tsx
 *
 * Formulário para abertura de um novo chamado de TI.
 * Visão do Solicitante — Fase 4, Passo 2.
 */

import { useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api, type TicketPriority } from '@/lib/api';
import { useAuth } from '@/context/AuthContext';
import { useToast } from '@/context/ToastContext';
import styles from './NewTicketPage.module.css';

// ─── Dados estáticos dos selects ──────────────────────────────────────────────

const PRIORITIES: { value: TicketPriority; label: string; description: string }[] = [
  { value: 'low',      label: '🟢 Baixa',    description: 'Sem impacto imediato' },
  { value: 'medium',   label: '🔵 Média',    description: 'Impacto moderado' },
  { value: 'high',     label: '🟡 Alta',     description: 'Impacto significativo' },
  { value: 'critical', label: '🔴 Crítica',  description: 'Sistema/serviço fora do ar' },
];

// ─── Componente ───────────────────────────────────────────────────────────────

export default function NewTicketPage() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { user } = useAuth();
  const { addToast } = useToast();

  // Estado do formulário
  const [title,       setTitle]      = useState('');
  const [description, setDesc]       = useState('');
  const [priority,    setPriority]   = useState<TicketPriority>('medium');
  const [categoryId,  setCategoryId] = useState<number | undefined>(undefined);

  // Query: categorias
  const { data: categories = [], isLoading: isLoadingCategories } = useQuery({
    queryKey: ['categories'],
    queryFn: () => api.categories.list(),
  });

  // Mutation: criação do ticket via API
  const { mutate: createTicket, isPending } = useMutation({
    mutationFn: () =>
      api.tickets.create({
        title:       title.trim(),
        description: description.trim(),
        priority,
        categoryId,
        creatorId:   user!.id,
      }),
    onSuccess: (data) => {
      void queryClient.invalidateQueries({ queryKey: ['tickets'] });
      addToast('Chamado criado com sucesso!', 'success');
      navigate(`/tickets/${data.id}`);
    },
    onError: (err: any) => {
      addToast(`Erro ao criar chamado: ${err.message}`, 'error');
    },
  });

  function handleSubmit(e: FormEvent) {
    e.preventDefault();
    createTicket();
  }

  return (
    <div className={styles.page}>

      {/* Cabeçalho da página */}
      <div className={styles.header}>
        <h2 className={styles.heading}>Novo Chamado</h2>
        <p className={styles.subheading}>
          Descreva o problema com o máximo de detalhes possível para agilizar o atendimento.
        </p>
      </div>

      {/* Formulário */}
      <form className={styles.form} onSubmit={handleSubmit} noValidate>

        {/* Título */}
        <div className={styles.fieldGroup}>
          <label htmlFor="ticket-title" className={styles.label}>
            Título <span className={styles.required} aria-hidden="true">*</span>
          </label>
          <input
            id="ticket-title"
            type="text"
            className="input"
            placeholder="Ex: Computador não liga após atualização"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
            minLength={5}
            maxLength={150}
            disabled={isPending}
            aria-describedby="title-hint"
          />
          <p id="title-hint" className={styles.hint}>
            Seja objetivo — este é o resumo que aparece na fila dos agentes.
          </p>
        </div>

        {/* Descrição */}
        <div className={styles.fieldGroup}>
          <label htmlFor="ticket-description" className={styles.label}>
            Descrição detalhada <span className={styles.required} aria-hidden="true">*</span>
          </label>
          <textarea
            id="ticket-description"
            className={`input ${styles.textarea}`}
            placeholder="Descreva o que aconteceu, quando começou, quais passos já foram tentados e o impacto no seu trabalho..."
            value={description}
            onChange={(e) => setDesc(e.target.value)}
            required
            minLength={10}
            rows={6}
            disabled={isPending}
          />
        </div>

        {/* Linha: Prioridade + Categoria */}
        <div className={styles.row}>

          {/* Prioridade */}
          <div className={styles.fieldGroup}>
            <label htmlFor="ticket-priority" className={styles.label}>
              Prioridade
            </label>
            <select
              id="ticket-priority"
              className="input"
              value={priority}
              onChange={(e) => setPriority(e.target.value as TicketPriority)}
              disabled={isPending}
            >
              {PRIORITIES.map((p) => (
                <option key={p.value} value={p.value}>
                  {p.label} — {p.description}
                </option>
              ))}
            </select>
          </div>

          {/* Categoria */}
          <div className={styles.fieldGroup}>
            <label htmlFor="ticket-category" className={styles.label}>
              Categoria
            </label>
            <select
              id="ticket-category"
              className="input"
              value={categoryId ?? ''}
              onChange={(e) =>
                setCategoryId(e.target.value ? Number(e.target.value) : undefined)
              }
              disabled={isPending || isLoadingCategories}
            >
              <option value="">Selecione uma categoria...</option>
              {categories.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Ações */}
        <div className={styles.actions}>
          <button
            type="button"
            className="btn btn--ghost"
            onClick={() => navigate('/dashboard')}
            disabled={isPending}
          >
            Cancelar
          </button>

          <button
            type="submit"
            className="btn btn--primary"
            disabled={isPending || title.trim().length < 5 || description.trim().length < 10}
            aria-busy={isPending}
          >
            {isPending ? (
              <>
                <span className="spinner" style={{ width: 16, height: 16, borderWidth: 2 }} />
                Enviando...
              </>
            ) : (
              'Abrir Chamado'
            )}
          </button>
        </div>

      </form>
    </div>
  );
}