v-sistec-features 1.31.11 → 1.31.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,216 @@
1
+ // ============================================================================
2
+ // Composable utilitário que centraliza cálculos de datas semanais, formatação
3
+ // de horários, busca de matriz na API, mesclagem de reservas contínuas e
4
+ // sincronização de recurso único entre os diferentes modelos de agenda.
5
+ // ============================================================================
6
+
7
+ import { ref, computed, watch, onMounted } from 'vue';
8
+ import { useAgenda } from './useAgenda';
9
+
10
+ export const SIGLAS_DIAS_JS = ['DOM', 'SEG', 'TER', 'QUA', 'QUI', 'SEX', 'SAB'];
11
+
12
+ export const TITULOS_DIAS_CABECALHO = [
13
+ 'DOMINGO',
14
+ '2ª FEIRA',
15
+ '3ª FEIRA',
16
+ '4ª FEIRA',
17
+ '5ª FEIRA',
18
+ '6ª FEIRA',
19
+ 'SÁBADO'
20
+ ];
21
+
22
+ // Recebe uma string ISO UTC e devolve objeto com data (YYYY-MM-DD) e hora (HH:MM) locais.
23
+ export const extrairDataHoraLocal = (isoString: string) => {
24
+ const d = new Date(isoString);
25
+ const ano = d.getFullYear();
26
+ const mes = String(d.getMonth() + 1).padStart(2, '0');
27
+ const dia = String(d.getDate()).padStart(2, '0');
28
+ const horas = String(d.getHours()).padStart(2, '0');
29
+ const min = String(d.getMinutes()).padStart(2, '0');
30
+ return { data: `${ano}-${mes}-${dia}`, hora: `${horas}:${min}` };
31
+ };
32
+
33
+ // Recebe uma string ISO UTC e devolve apenas o horário local formatado em HH:MM.
34
+ export const extrairHoraFormatada = (isoStr: string) => {
35
+ const d = new Date(isoStr);
36
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
37
+ };
38
+
39
+ // Recebe uma string YYYY-MM-DD ou Date e devolve um objeto Date local zerado no início do dia.
40
+ export const criarDataLocal = (valorData: string | Date) => {
41
+ if (typeof valorData === 'string') {
42
+ const [ano, mes, dia] = valorData.substring(0, 10).split('-').map(Number);
43
+ return new Date(ano!, mes! - 1, dia!);
44
+ }
45
+ return new Date(valorData.getFullYear(), valorData.getMonth(), valorData.getDate());
46
+ };
47
+
48
+ // Recebe um objeto Date e devolve a string correspondente no formato YYYY-MM-DD.
49
+ export const formatarDataIso = (dt: Date) => {
50
+ const ano = dt.getFullYear();
51
+ const mes = String(dt.getMonth() + 1).padStart(2, '0');
52
+ const dia = String(dt.getDate()).padStart(2, '0');
53
+ return `${ano}-${mes}-${dia}`;
54
+ };
55
+
56
+ // Recebe a data de referência e o dia inicial no formato Python (0=SEG..6=DOM) e devolve o Date do início da semana.
57
+ export const calcularDataInicioSemana = (dataRef: string | Date, diaInicioPython = 0) => {
58
+ const d = criarDataLocal(dataRef);
59
+ const diaInicioJs = (Number(diaInicioPython) + 1) % 7;
60
+ const diff = (d.getDay() - diaInicioJs + 7) % 7;
61
+ d.setDate(d.getDate() - diff);
62
+ return d;
63
+ };
64
+
65
+ // Recebe a lista de slots disponíveis de um recurso e a chave de span ('colspan' ou 'rowspan').
66
+ // Devolve a lista de células com reservas consecutivas de mesmo código mescladas.
67
+ export const mesclarSlotsReservados = (slotsBrutos: any[], chaveSpan: 'colspan' | 'rowspan') => {
68
+ const chaveIndice = chaveSpan === 'colspan' ? 'indiceColuna' : 'indiceLinha';
69
+ const chaveOculta = chaveSpan === 'colspan' ? 'ocultaPorColspan' : 'ocultaPorRowspan';
70
+ const celulasMescladas: any[] = [];
71
+
72
+ let i = 0;
73
+ while (i < slotsBrutos.length) {
74
+ const slotAtual = slotsBrutos[i];
75
+ const codRef = slotAtual?.detalhes_reserva?.codigo_referencia_reserva;
76
+
77
+ if (slotAtual?.reservado_slot && codRef) {
78
+ let span = 1;
79
+ while (
80
+ i + span < slotsBrutos.length &&
81
+ slotsBrutos[i + span]?.reservado_slot &&
82
+ slotsBrutos[i + span]?.detalhes_reserva?.codigo_referencia_reserva === codRef
83
+ ) {
84
+ span++;
85
+ }
86
+
87
+ celulasMescladas.push({
88
+ ...slotAtual,
89
+ [chaveIndice]: i,
90
+ [chaveSpan]: span,
91
+ [chaveOculta]: false
92
+ });
93
+
94
+ for (let k = 1; k < span; k++) {
95
+ celulasMescladas.push({
96
+ ...slotsBrutos[i + k],
97
+ [chaveIndice]: i + k,
98
+ [chaveSpan]: 1,
99
+ [chaveOculta]: true
100
+ });
101
+ }
102
+ i += span;
103
+ } else {
104
+ celulasMescladas.push({
105
+ ...slotAtual,
106
+ [chaveIndice]: i,
107
+ [chaveSpan]: 1,
108
+ [chaveOculta]: false
109
+ });
110
+ i++;
111
+ }
112
+ }
113
+
114
+ return celulasMescladas;
115
+ };
116
+
117
+ // Gerencia o ciclo de busca semanal da matriz, estados de modais e configuração de blocos por agenda.
118
+ export function useGradeSemanal(api: any, obterConfiguracaoBlocos?: () => any) {
119
+ const {
120
+ dadosMatrix,
121
+ buscarSlotsMatrix,
122
+ buscarReservas,
123
+ agendasDisponiveis,
124
+ agendaSelecionada,
125
+ dataSelecionada,
126
+ converterParaUtc
127
+ } = useAgenda(api);
128
+
129
+ const carregando = ref(false);
130
+ const modalAberto = ref(false);
131
+ const dadosParaModal = ref({});
132
+ const modalDetalhesAberto = ref(false);
133
+ const reservaSelecionadaDetalhes = ref<any>(null);
134
+
135
+ const dispararBuscaSemanal = async () => {
136
+ const idAgenda = agendaSelecionada.value;
137
+ if (!idAgenda) return;
138
+
139
+ carregando.value = true;
140
+ const agendaObj = agendasDisponiveis.value.find((a: any) => Number(a.id_agenda) === Number(idAgenda));
141
+ const diaInicioPython = agendaObj?.detalhes?.dia_inicio_semana_agenda ?? 0;
142
+
143
+ const dataInicio = calcularDataInicioSemana(dataSelecionada.value || new Date(), diaInicioPython);
144
+ const dataFim = new Date(dataInicio);
145
+ dataFim.setDate(dataInicio.getDate() + 6);
146
+
147
+ const strInicio = formatarDataIso(dataInicio);
148
+ const strFim = formatarDataIso(dataFim);
149
+
150
+ const inicioUtc = encodeURIComponent(converterParaUtc(strInicio, '00:00'));
151
+ const fimUtc = encodeURIComponent(converterParaUtc(strFim, '23:59'));
152
+
153
+ await buscarSlotsMatrix(idAgenda, inicioUtc, fimUtc);
154
+ await buscarReservas(`${strInicio}T00:00:00`, `${strFim}T23:59:59`);
155
+ carregando.value = false;
156
+ };
157
+
158
+ onMounted(dispararBuscaSemanal);
159
+ watch([dataSelecionada, agendaSelecionada], dispararBuscaSemanal);
160
+
161
+ const configuracaoAgendaAtual = computed(() => {
162
+ const configBruta = obterConfiguracaoBlocos ? obterConfiguracaoBlocos() : null;
163
+ if (!configBruta || !agendaSelecionada.value) return null;
164
+ const idAtual = Number(agendaSelecionada.value);
165
+
166
+ if (Array.isArray(configBruta)) {
167
+ return configBruta.find((c: any) => Number(c.id_agenda) === idAtual) || null;
168
+ }
169
+ if (typeof configBruta === 'object') {
170
+ if (Number(configBruta.id_agenda) === idAtual) return configBruta;
171
+ if (configBruta[idAtual]) return configBruta[idAtual];
172
+ }
173
+ return null;
174
+ });
175
+
176
+ // Extrai a lista de blocos configurados para um dia específico da semana ou padrão da agenda.
177
+ const obterBlocosDoDia = (siglaDia: string): any[] | null => {
178
+ const cfg = configuracaoAgendaAtual.value;
179
+ if (!cfg) return null;
180
+ if (cfg.por_dia && cfg.por_dia[siglaDia]) return cfg.por_dia[siglaDia];
181
+ if (Array.isArray(cfg.blocos)) return cfg.blocos;
182
+ return null;
183
+ };
184
+
185
+ return {
186
+ dadosMatrix,
187
+ carregando,
188
+ modalAberto,
189
+ dadosParaModal,
190
+ modalDetalhesAberto,
191
+ reservaSelecionadaDetalhes,
192
+ configuracaoAgendaAtual,
193
+ obterBlocosDoDia,
194
+ dispararBuscaSemanal
195
+ };
196
+ }
197
+
198
+ // Sincroniza automaticamente o recursoSelecionado e a agendaSelecionada quando um ID de recurso fixo é informado.
199
+ export function useSincronizarRecursoUnico(api: any, obterIdRecurso: () => number | string | null | undefined) {
200
+ const { recursosDisponiveis, agendaSelecionada, recursoSelecionado } = useAgenda(api);
201
+
202
+ watch([obterIdRecurso, recursosDisponiveis], ([idRec]) => {
203
+ if (!idRec || recursosDisponiveis.value.length === 0) return;
204
+
205
+ const encontrado = recursosDisponiveis.value.find(
206
+ (r: any) => Number(r.id_recurso) === Number(idRec)
207
+ );
208
+
209
+ if (encontrado) {
210
+ recursoSelecionado.value = Number(encontrado.id_recurso);
211
+ if (encontrado.id_agenda && agendaSelecionada.value !== encontrado.id_agenda) {
212
+ agendaSelecionada.value = encontrado.id_agenda;
213
+ }
214
+ }
215
+ }, { immediate: true });
216
+ }
@@ -0,0 +1,167 @@
1
+ /*
2
+ ========
3
+ Este arquivo implementa um gerenciador genérico e agnóstico de seleção por arrasto (drag-to-select).
4
+ Ele permite selecionar intervalos contínuos de itens em um mesmo eixo (horizontal ou vertical),
5
+ validando se há itens desabilitados no caminho e devolvendo a lista de dados selecionados ao final.
6
+ ========
7
+ */
8
+ import { ref, onMounted, onUnmounted } from 'vue';
9
+
10
+ interface OpcoesSelecaoArrasto<T = any> {
11
+ obterListaDoGrupo?: (grupo: string | number) => T[];
12
+ validarItemDisponivel?: (item: T) => boolean;
13
+ aoFinalizarSelecao?: (dados: {
14
+ grupo: string | number;
15
+ indiceInicial: number;
16
+ indiceFinal: number;
17
+ itensSelecionados: T[];
18
+ }) => void;
19
+ aoClicarItemIndisponivel?: (item: T, grupo: string | number, indice: number) => void;
20
+ }
21
+
22
+ export function useSelecaoArrasto<T = any>(opcoes: OpcoesSelecaoArrasto<T> = {}) {
23
+ const arrastando = ref(false);
24
+ const grupoAtivo = ref<string | number | null>(null);
25
+ const indiceInicio = ref<number | null>(null);
26
+ const indiceFim = ref<number | null>(null);
27
+
28
+ const mapaItensRegistrados = new Map<string | number, Map<number, { item: T; disponivel: boolean }>>();
29
+
30
+ const registrarItemNoMapa = (grupo: string | number, indice: number, item: T, disponivel: boolean) => {
31
+ if (!mapaItensRegistrados.has(grupo)) {
32
+ mapaItensRegistrados.set(grupo, new Map());
33
+ }
34
+ mapaItensRegistrados.get(grupo)!.set(indice, { item, disponivel });
35
+ };
36
+
37
+ const removerItemDoMapa = (grupo: string | number, indice: number) => {
38
+ const submapa = mapaItensRegistrados.get(grupo);
39
+ if (submapa) {
40
+ submapa.delete(indice);
41
+ if (submapa.size === 0) mapaItensRegistrados.delete(grupo);
42
+ }
43
+ };
44
+
45
+ const verificarSelecionado = (grupo: string | number, indice: number): boolean => {
46
+ if (!arrastando.value || grupoAtivo.value !== grupo) return false;
47
+ if (indiceInicio.value === null || indiceFim.value === null) return false;
48
+ const menor = Math.min(indiceInicio.value, indiceFim.value);
49
+ const maior = Math.max(indiceInicio.value, indiceFim.value);
50
+ return indice >= menor && indice <= maior;
51
+ };
52
+
53
+ const iniciarArrasto = (grupo: string | number, indice: number, item: T, disponivel = true) => {
54
+ const podeSelecionar = opcoes.validarItemDisponivel
55
+ ? opcoes.validarItemDisponivel(item)
56
+ : disponivel;
57
+
58
+ if (!podeSelecionar) {
59
+ if (opcoes.aoClicarItemIndisponivel) {
60
+ opcoes.aoClicarItemIndisponivel(item, grupo, indice);
61
+ }
62
+ return;
63
+ }
64
+
65
+ arrastando.value = true;
66
+ grupoAtivo.value = grupo;
67
+ indiceInicio.value = indice;
68
+ indiceFim.value = indice;
69
+ };
70
+
71
+ const atualizarArrasto = (grupo: string | number, indice: number) => {
72
+ if (!arrastando.value || grupoAtivo.value !== grupo || indiceInicio.value === null) return;
73
+
74
+ const menorTentativa = Math.min(indiceInicio.value, indice);
75
+ const maiorTentativa = Math.max(indiceInicio.value, indice);
76
+
77
+ if (opcoes.obterListaDoGrupo && opcoes.validarItemDisponivel) {
78
+ const listaGrupo = opcoes.obterListaDoGrupo(grupo);
79
+ for (let i = menorTentativa; i <= maiorTentativa; i++) {
80
+ const itemVerificacao = listaGrupo[i];
81
+ if (!itemVerificacao || !opcoes.validarItemDisponivel(itemVerificacao)) {
82
+ return;
83
+ }
84
+ }
85
+ } else {
86
+ const submapa = mapaItensRegistrados.get(grupo);
87
+ if (submapa) {
88
+ for (let i = menorTentativa; i <= maiorTentativa; i++) {
89
+ const registro = submapa.get(i);
90
+ if (!registro || !registro.disponivel) {
91
+ return;
92
+ }
93
+ }
94
+ }
95
+ }
96
+
97
+ indiceFim.value = indice;
98
+ };
99
+
100
+ const finalizarArrasto = () => {
101
+ if (!arrastando.value) return;
102
+
103
+ const grupoFinal = grupoAtivo.value;
104
+ const ini = indiceInicio.value;
105
+ const fim = indiceFim.value;
106
+
107
+ arrastando.value = false;
108
+ grupoAtivo.value = null;
109
+ indiceInicio.value = null;
110
+ indiceFim.value = null;
111
+
112
+ if (grupoFinal === null || ini === null || fim === null) return;
113
+
114
+ const menor = Math.min(ini, fim);
115
+ const maior = Math.max(ini, fim);
116
+ const itensSelecionados: T[] = [];
117
+
118
+ if (opcoes.obterListaDoGrupo) {
119
+ const listaGrupo = opcoes.obterListaDoGrupo(grupoFinal);
120
+ for (let i = menor; i <= maior; i++) {
121
+ const itemLocalizado = listaGrupo[i];
122
+ // Tipagem forte para garantir ao TS que a conversão é segura.
123
+ if (itemLocalizado !== undefined) {
124
+ itensSelecionados.push(itemLocalizado as T);
125
+ }
126
+ }
127
+ } else {
128
+ const submapa = mapaItensRegistrados.get(grupoFinal);
129
+ if (submapa) {
130
+ for (let i = menor; i <= maior; i++) {
131
+ const reg = submapa.get(i);
132
+ if (reg) itensSelecionados.push(reg.item);
133
+ }
134
+ }
135
+ }
136
+
137
+ if (itensSelecionados.length > 0 && opcoes.aoFinalizarSelecao) {
138
+ opcoes.aoFinalizarSelecao({
139
+ grupo: grupoFinal,
140
+ indiceInicial: menor,
141
+ indiceFinal: maior,
142
+ itensSelecionados
143
+ });
144
+ }
145
+ };
146
+
147
+ onMounted(() => {
148
+ window.addEventListener('mouseup', finalizarArrasto);
149
+ });
150
+
151
+ onUnmounted(() => {
152
+ window.removeEventListener('mouseup', finalizarArrasto);
153
+ });
154
+
155
+ return {
156
+ arrastando,
157
+ grupoAtivo,
158
+ indiceInicio,
159
+ indiceFim,
160
+ verificarSelecionado,
161
+ iniciarArrasto,
162
+ atualizarArrasto,
163
+ finalizarArrasto,
164
+ registrarItemNoMapa,
165
+ removerItemDoMapa
166
+ };
167
+ }