etiquetas.js 1.0.0-alpha.1 → 1.0.0-alpha.11

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.
Files changed (40) hide show
  1. package/README.md +122 -38
  2. package/README.npm.md +0 -0
  3. package/dist/etiquetas.es.js +65 -0
  4. package/dist/etiquetas.es.js.map +1 -0
  5. package/dist/etiquetas.umd.js +358 -0
  6. package/dist/etiquetas.umd.js.map +1 -0
  7. package/dist/index-Bl0CvwuC.js +59982 -0
  8. package/dist/index-Bl0CvwuC.js.map +1 -0
  9. package/dist/index.es-eEPQXFRd.js +9229 -0
  10. package/dist/index.es-eEPQXFRd.js.map +1 -0
  11. package/dist/purify.es-DzZgBtzL.js +965 -0
  12. package/dist/purify.es-DzZgBtzL.js.map +1 -0
  13. package/package.json +38 -14
  14. package/README.git.md +0 -486
  15. package/api/api-labels.json +0 -114
  16. package/api/api.js +0 -316
  17. package/api/mock/data-volume-id_680.json +0 -64
  18. package/api/mock/labels-input.json +0 -96
  19. package/api/mock/labels-part.json +0 -216
  20. package/api/mock/labels-scrap.json +0 -76
  21. package/api/mock/labels-thickened.json +0 -96
  22. package/api/mock/labels-volume.json +0 -56
  23. package/api/token.txt +0 -1
  24. package/services/index.js +0 -28
  25. package/src/constants.js +0 -247
  26. package/src/createLabel.js +0 -342
  27. package/src/etiquetas.js +0 -654
  28. package/src/formatData.js +0 -96
  29. package/src/formatDataIntegrated.js +0 -498
  30. package/src/index.js +0 -86
  31. package/src/label/services/index.js +0 -1201
  32. package/src/label/services/sortFunctions.js +0 -158
  33. package/src/label/services/utils.js +0 -280
  34. package/src/labelWorker.js +0 -123
  35. package/src/reducer.js +0 -40
  36. package/src/store.js +0 -55
  37. package/src/templates.js +0 -139
  38. package/src/useLabelData.js +0 -99
  39. package/src/usePrinterStore.js +0 -115
  40. package/src/variableManager.js +0 -224
package/src/templates.js DELETED
@@ -1,139 +0,0 @@
1
- /**
2
- * 🏷️ TEMPLATES DO SISTEMA DE ETIQUETAS
3
- *
4
- * Configurações e definições de templates para cada tipo de etiqueta
5
- */
6
-
7
- import { templateVariables } from './constants.js';
8
- import { LabelsAPI } from '../api/api.js';
9
-
10
- // ============================================================================
11
- // TEMPLATES DE PEÇAS
12
- // ============================================================================
13
-
14
-
15
- /**
16
- * Obtém um template pelo seu ID a partir da API de etiquetas
17
- * @param {number|string} templateId - ID do template/etiqueta a buscar
18
- * @returns {Promise<Object>} Template com dados da API
19
- */
20
- export async function getTemplateById(templateId) {
21
- try {
22
- // Converte para número se for string numérica
23
-
24
-
25
-
26
- // Busca na API pelo ID
27
- const labelData = await LabelsAPI.getLabel(templateId);
28
-
29
- if (!labelData) {
30
- throw new Error(`Template/etiqueta não encontrado com ID: ${templateId}`);
31
- }
32
-
33
-
34
-
35
-
36
- // Retorna em formato de array conforme esperado pela função loadLabelTemplate
37
- console.log('templateContent:', labelData);
38
- return JSON.parse(labelData.label_content);
39
- } catch (error) {
40
- console.error(`Erro ao buscar template: ${error.message}`);
41
- throw error;
42
- }
43
- }
44
-
45
- /**
46
- * Obtém templates por tipo
47
- * @param {string} type - Tipo de etiqueta (parts, woodwork, inputs, scraps, volumes)
48
- * @returns {Array} Lista de templates do tipo especificado
49
- */
50
- export function getTemplatesByType(type) {
51
- return Object.values(allTemplates).filter(template => template.type === type);
52
- }
53
-
54
- /**
55
- * Lista todos os IDs de templates disponíveis
56
- * @returns {Array} Lista de IDs de templates
57
- */
58
- export function getTemplateIds() {
59
- return Object.keys(allTemplates);
60
- }
61
-
62
- /**
63
- * Valida se um template possui estrutura válida
64
- * @param {Object} template - Template a ser validado
65
- * @returns {boolean} True se válido, false caso contrário
66
- */
67
- export function validateTemplate(template) {
68
- if (!template || typeof template !== 'object') return false;
69
-
70
- const requiredFields = ['id', 'name', 'type', 'pageWidth', 'pageHeight', 'elements'];
71
-
72
- for (const field of requiredFields) {
73
- if (!(field in template)) return false;
74
- }
75
-
76
- if (!Array.isArray(template.elements)) return false;
77
-
78
- return true;
79
- }
80
-
81
- /**
82
- * Obtém variáveis utilizadas em um template
83
- * @param {Object} template - Template a ser analisado
84
- * @returns {Array} Lista de variáveis encontradas
85
- */
86
- export function getTemplateVariables(template) {
87
- if (!validateTemplate(template)) return [];
88
-
89
- const variables = new Set();
90
- const variableRegex = /\{\{([^}]+)\}\}/g;
91
-
92
- template.elements.forEach(element => {
93
- if (element.content) {
94
- let match;
95
- while ((match = variableRegex.exec(element.content)) !== null) {
96
- variables.add(match[1]);
97
- }
98
- }
99
- });
100
-
101
- return Array.from(variables);
102
- }
103
-
104
- /**
105
- * Substitui variáveis em um template com dados fornecidos
106
- * @param {Object} template - Template base
107
- * @param {Object} data - Dados para substituição
108
- * @returns {Object} Template com variáveis substituídas
109
- */
110
- export function replaceTemplateVariables(template, data) {
111
- if (!validateTemplate(template)) return template;
112
-
113
- const processedTemplate = JSON.parse(JSON.stringify(template));
114
-
115
- processedTemplate.elements = processedTemplate.elements.map(element => {
116
- if (element.content) {
117
- element.content = element.content.replace(/\{\{([^}]+)\}\}/g, (match, variable) => {
118
- return data[variable] || match;
119
- });
120
- }
121
- return element;
122
- });
123
-
124
- return processedTemplate;
125
- }
126
-
127
- // ============================================================================
128
- // EXPORTAÇÃO PADRÃO
129
- // ============================================================================
130
-
131
- export default {
132
-
133
- getTemplateById,
134
- getTemplatesByType,
135
- getTemplateIds,
136
- validateTemplate,
137
- getTemplateVariables,
138
- replaceTemplateVariables
139
- };
@@ -1,99 +0,0 @@
1
- // Imports básicos para o pacote npm
2
- import { getPartsForLabels, getPartsFromProjectToLabels } from './formatData.js';
3
- import { createLabelWorker } from './labelWorker.js';
4
- import { labelTypeNames } from './constants.js';
5
-
6
- /**
7
- * Hook simplificado para uso em pacote npm
8
- * Retorna funções utilitárias para trabalhar com dados de etiquetas
9
- */
10
- export const useLabelData = (config = {}) => {
11
- // Configuração padrão
12
- const defaultConfig = {
13
- type: 'parts',
14
- category: [],
15
- specific: false,
16
- dataIndex: null,
17
- otherData: null,
18
- source: null
19
- };
20
-
21
- const finalConfig = { ...defaultConfig, ...config };
22
-
23
- // Função para gerar etiquetas com dados fornecidos
24
- const generateLabels = async (data, labels, userPrefs = {}, additionalParams = {}) => {
25
- const worker = createLabelWorker();
26
-
27
- const params = {
28
- dataSource: data || [],
29
- labels: labels || [],
30
- userPrefs: userPrefs,
31
- cacheKey: `label-${Date.now()}`,
32
- ...additionalParams
33
- };
34
-
35
- return await worker.generateLabels(params);
36
- };
37
-
38
- // Função para download de PDF (compatível com Node.js)
39
- const downloadPDF = (pdfBlob, filename = 'etiqueta.pdf') => {
40
- // Em ambiente Node.js, retorna os dados do blob para processamento externo
41
- if (typeof window === 'undefined') {
42
- return pdfBlob;
43
- }
44
-
45
- // Em ambiente browser, mantém funcionalidade original
46
- const url = URL.createObjectURL(pdfBlob);
47
- const link = document.createElement('a');
48
- link.href = url;
49
- link.download = filename;
50
- document.body.appendChild(link);
51
- link.click();
52
- document.body.removeChild(link);
53
- URL.revokeObjectURL(url);
54
- };
55
-
56
- // Função para verificar disponibilidade da impressora
57
- const checkPrinterAvailability = async () => {
58
- try {
59
- // Implementação básica - pode ser expandida
60
- return false;
61
- } catch (error) {
62
- console.warn('Não foi possível verificar impressoras:', error);
63
- return false;
64
- }
65
- };
66
-
67
- // Função para obter dados formatados de peças
68
- const getLabelData = (type = 'parts') => {
69
- return {
70
- data: [],
71
- label: [],
72
- userPrefs: {},
73
- cacheKey: `${type}-${Date.now()}`
74
- };
75
- };
76
-
77
- return {
78
- // Estado
79
- isReady: true,
80
- isGenerating: false,
81
- progress: 0,
82
- error: null,
83
-
84
- // Dados
85
- data: [],
86
- label: [],
87
- userPrefs: {},
88
- cacheKey: `label-${Date.now()}`,
89
-
90
- // Métodos
91
- generateLabels,
92
- downloadPDF,
93
- checkPrinterAvailability,
94
- getLabelData,
95
-
96
- // Configuração
97
- config: finalConfig
98
- };
99
- };
@@ -1,115 +0,0 @@
1
- import { create } from 'zustand';
2
-
3
- const createPrinterSlice = (set, get) => ({
4
- printerStatus: {
5
- name: 'Aguardando...',
6
- connected: false,
7
- status: 'disconnected',
8
- hasDefaultPrinter: false,
9
- message: 'Conectando ao servidor...',
10
- printer: null
11
- },
12
- setPrinterStatus: (status) => set(() => ({ printerStatus: status })),
13
- updatePrinterStatus: (updates) => set((state) => ({
14
- printerStatus: { ...state.printerStatus, ...updates }
15
- }))
16
- });
17
-
18
- const createSSESlice = (set, get) => ({
19
- sseConnected: false,
20
- eventSource: null,
21
- setSseConnected: (connected) => set(() => ({ sseConnected: connected })),
22
- setEventSource: (eventSource) => set(() => ({ eventSource })),
23
-
24
- connectToSSE: () => {
25
- const { eventSource, setSseConnected, updatePrinterStatus, setEventSource } = get();
26
-
27
- // Verificar se estamos em ambiente browser
28
- if (typeof EventSource === 'undefined') {
29
- console.log('EventSource não disponível em ambiente Node.js');
30
- setSseConnected(false);
31
- updatePrinterStatus({ connected: false, status: 'disconnected' });
32
- return;
33
- }
34
-
35
- // Se já existe uma conexão, feche-a primeiro
36
- if (eventSource) {
37
- eventSource.close();
38
- }
39
-
40
- try {
41
- const newEventSource = new EventSource('http://localhost:9999/printer/status/stream');
42
- setEventSource(newEventSource);
43
-
44
- newEventSource.onopen = () => {
45
- console.log('Conexão SSE estabelecida com a impressora');
46
- setSseConnected(true);
47
- updatePrinterStatus({ status: 'connecting' });
48
- };
49
-
50
- newEventSource.addEventListener('printer-status', (event) => {
51
- try {
52
- const data = JSON.parse(event.data);
53
- console.log('message =>>>>>>>>>',data);
54
- let status = 'disconnected';
55
- let name = 'Nenhuma impressora';
56
-
57
- if (!data.hasDefaultPrinter) {
58
- status = 'no-printer';
59
- name = 'Sem impressora configurada';
60
- } else if (data.isConnected && data.printer) {
61
- status = 'connected';
62
- name = data.printer.name || 'Impressora';
63
- } else {
64
- status = 'disconnected';
65
- name = data.printer?.name || 'Impressora';
66
- }
67
-
68
- updatePrinterStatus({
69
- name,
70
- connected: data.isConnected || false,
71
- status,
72
- hasDefaultPrinter: data.hasDefaultPrinter || false,
73
- message: data.message || '',
74
- printer: data.printer || null
75
- });
76
- } catch (error) {
77
- console.error('Erro ao processar dados da impressora:', error);
78
- }
79
- });
80
-
81
- newEventSource.onerror = (error) => {
82
- console.error('Erro na conexão SSE:', error);
83
- setSseConnected(false);
84
- updatePrinterStatus({ connected: false, status: 'disconnected' });
85
- newEventSource.close();
86
- setEventSource(null);
87
-
88
- // Tentar reconectar após 5 segundos
89
- setTimeout(() => {
90
- get().connectToSSE();
91
- }, 5000);
92
- };
93
- } catch (error) {
94
- console.error('Erro ao conectar SSE:', error);
95
- setSseConnected(false);
96
- updatePrinterStatus({ connected: false, status: 'disconnected' });
97
- }
98
- },
99
-
100
- disconnectSSE: () => {
101
- const { eventSource, setSseConnected, setEventSource } = get();
102
- if (eventSource) {
103
- eventSource.close();
104
- setEventSource(null);
105
- }
106
- setSseConnected(false);
107
- }
108
- });
109
-
110
- const usePrinterStore = create((set, get) => ({
111
- ...createPrinterSlice(set, get),
112
- ...createSSESlice(set, get)
113
- }));
114
-
115
- export default usePrinterStore;
@@ -1,224 +0,0 @@
1
- /**
2
- * Gerenciador de variáveis para templates de etiquetas
3
- * Centraliza a lógica de mapeamento entre placeholders e dados reais
4
- */
5
-
6
- class VariableManager {
7
- constructor() {
8
- // Define os placeholders disponíveis
9
- this.templateVariables = [
10
- "{{PROJETO_ID}}",
11
- "{{PROJETO_NOME}}",
12
- "{{PROJETO_OBS}}",
13
- "{{CLIENTE_ID}}",
14
- "{{CLIENTE_NOME}}",
15
- "{{PECA_ID}}",
16
- "{{PECA_CODIGO}}",
17
- "{{PECA_REF}}",
18
- "{{MODULO_REF}}",
19
- "{{PECA_INDICE}}",
20
- "{{PECA_INDICE2}}",
21
- "{{PECA_REF}}",
22
- "{{PECA_NOME}}",
23
- "{{PECA_OBS}}",
24
- "{{LARGURA}}",
25
- "{{ALTURA}}",
26
- "{{ESPESSURA}}",
27
- "{{MN}}",
28
- "{{MA}}",
29
- "{{ML}}",
30
- "{{FURO_A}}",
31
- "{{FURO_A2}}",
32
- "{{FURO_B}}",
33
- "{{FURO_B2}}",
34
- "{{FE}}",
35
- "{{FD}}",
36
- "{{FS}}",
37
- "{{FI}}",
38
- "{{INSUMO_NOME}}",
39
- "{{INSUMO_ID}}",
40
- "{{INSUMO_DIMENSOES}}",
41
- "{{INSUMO_QTD}}",
42
- "{{INSUMO_PESO}}",
43
- "{{INSUMO_REF}}",
44
- "{{INSUMO_MARCA}}",
45
- "{{TAMPONAMENTO_ID}}",
46
- "{{TAMPONAMENTO_REF}}",
47
- "{{TAMPONAMENTO_QT}}",
48
- "{{TAMPONAMENTO_PESO}}",
49
- "{{TAMPONAMENTO_NOME}}",
50
- "{{MATERIAL_NOME}}",
51
- "{{PECA_TIPO}}",
52
- "{{MODULO_NOME}}",
53
- "{{LOTE_ID}}",
54
- "{{MODULO_OBS}}",
55
- "{{RETALHO_ID}}",
56
- "{{DATA_CRIACAO}}",
57
- "{{RETALHO_INDICE}}",
58
- "{{MODULO_PECAS}}",
59
- "{{LADO_USINAGEM}}",
60
- "{{VOLUME_ID}}",
61
- "{{VOLUME_NOME}}",
62
- "{{VOLUME_PESO}}",
63
- "{{VOLUME_DATA}}"
64
- ];
65
- }
66
-
67
- /**
68
- * Gera os valores correspondentes aos placeholders baseado nos dados da peça
69
- * @param {Object} partData - Dados da peça
70
- * @param {Object} partTypes - Tipos de peças disponíveis
71
- * @param {Object} options - Opções adicionais (como rotação)
72
- * @returns {Array} Array com os valores correspondentes aos placeholders
73
- */
74
- generateValues(partData, partTypes = {}, options = {}) {
75
- // Calcula largura e altura considerando rotação
76
- let partWidth = partData["width"];
77
- let partHeight = partData["height"];
78
-
79
- if (partData["rotated"]) {
80
- partWidth = partData["width"];
81
- partHeight = partData["height"];
82
- }
83
-
84
- return [
85
- partData["project_id"],
86
- partData["project_description"],
87
- partData["project_note"],
88
- partData["project_customer_id"],
89
- partData["project_customer_name"],
90
- partData["id"],
91
- partData["pid"],
92
- partData["pref"],
93
- partData["mref"],
94
- partData["index"],
95
- partData["number"],
96
- partData["ref"],
97
- partData["name"],
98
- partData["note"],
99
- partWidth,
100
- partHeight,
101
- partData["thickness"],
102
- partData["materialName"] || partData["material"] || partData["material_name"],
103
- partData["material_height"],
104
- partData["material_width"],
105
- partData["code_a"],
106
- partData["code_a2"],
107
- partData["code_b"],
108
- partData["code_b2"],
109
- partData["edge_left"],
110
- partData["edge_right"],
111
- partData["edge_top"],
112
- partData["edge_bottom"],
113
- partData["name"],
114
- partData["id"],
115
- partData["dimensions"],
116
- partData["qt"],
117
- partData["weight"],
118
- partData["ref"],
119
- partData["manufacturer"],
120
- partData["id"],
121
- partData["ref"],
122
- partData["qt"],
123
- partData["weight"],
124
- partData["name"],
125
- partData["material"],
126
- partTypes[partData["type"]],
127
- partData["mname"],
128
- partData["group_id"] || partData["groupId"],
129
- partData["mnote"],
130
- partData["scrapId"],
131
- partData["date"],
132
- partData["scrapId"],
133
- partData["moduleLength"],
134
- partData["machining_side"],
135
- partData["volume_id"],
136
- partData["volume_name"],
137
- partData["volume_weight"],
138
- partData["volume_date"]
139
- ];
140
- }
141
-
142
- /**
143
- * Substitui placeholders em um texto pelos valores reais
144
- * @param {string} text - Texto com placeholders
145
- * @param {Object} partData - Dados da peça
146
- * @param {Object} partTypes - Tipos de peças disponíveis
147
- * @param {Object} options - Opções adicionais
148
- * @returns {string} Texto com placeholders substituídos
149
- */
150
- replaceVariables(text, partData, partTypes = {}, options = {}) {
151
- const values = this.generateValues(partData, partTypes, options);
152
- return this.performReplacement(this.templateVariables, values, text);
153
- }
154
-
155
- /**
156
- * Função interna para realizar as substituições
157
- * @param {Array} search - Array de termos para buscar
158
- * @param {Array} replace - Array de valores para substituir
159
- * @param {string} subject - Texto onde fazer as substituições
160
- * @returns {string} Texto com substituições realizadas
161
- */
162
- performReplacement(search, replace, subject, countObj) {
163
- // Normalize inputs to arrays
164
- const searchArray = [].concat(search);
165
- const replaceArray = [].concat(replace);
166
- const subjectArray = [].concat(subject);
167
- const isReplaceArray = Array.isArray(replace);
168
- const isSubjectArray = Array.isArray(subject);
169
-
170
- // Handle case where search is array but replace is string - replicate string for each search
171
- const normalizedReplace = (Array.isArray(search) && typeof replace === "string")
172
- ? new Array(searchArray.length).fill(replace)
173
- : replaceArray;
174
-
175
- // Initialize count if provided
176
- if (countObj) countObj.value = 0;
177
-
178
- // Process each subject string
179
- const result = subjectArray.map(str => {
180
- if (str === "") return str;
181
-
182
- let processedStr = String(str);
183
- searchArray.forEach((searchTerm, index) => {
184
- const replacement = isReplaceArray
185
- ? (normalizedReplace[index] !== undefined ? normalizedReplace[index] : "")
186
- : normalizedReplace[0] || "";
187
-
188
- if (countObj) {
189
- countObj.value += processedStr.split(searchTerm).length - 1;
190
- }
191
- processedStr = processedStr.split(searchTerm).join(replacement);
192
- });
193
-
194
- return processedStr;
195
- });
196
-
197
- return isSubjectArray ? result : result[0];
198
- }
199
-
200
- /**
201
- * Retorna os placeholders disponíveis
202
- * @returns {Array} Array com todos os placeholders
203
- */
204
- getAvailableVariables() {
205
- return [...this.templateVariables];
206
- }
207
-
208
- /**
209
- * Método para compatibilidade com o código existente
210
- * Retorna inputs e outputs no formato antigo
211
- * @param {Object} partData - Dados da peça
212
- * @param {Object} partTypes - Tipos de peças disponíveis
213
- * @param {Object} options - Opções adicionais
214
- * @returns {Object} Objeto com inputs e outputs
215
- */
216
- getLegacyFormat(partData, partTypes = {}, options = {}) {
217
- return {
218
- inputs: this.templateVariables,
219
- outputs: this.generateValues(partData, partTypes, options)
220
- };
221
- }
222
- }
223
-
224
- export default VariableManager;