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

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.git.md +121 -486
  2. package/README.md +134 -1
  3. package/README.npm.md +0 -0
  4. package/dist/etiquetas.es.js +66 -0
  5. package/dist/etiquetas.es.js.map +1 -0
  6. package/dist/etiquetas.umd.js +358 -0
  7. package/dist/etiquetas.umd.js.map +1 -0
  8. package/dist/index-BmMBOPX1.js +59122 -0
  9. package/dist/index-BmMBOPX1.js.map +1 -0
  10. package/dist/index.es-DzWoeylQ.js +9229 -0
  11. package/dist/index.es-DzWoeylQ.js.map +1 -0
  12. package/dist/purify.es-DzZgBtzL.js +965 -0
  13. package/dist/purify.es-DzZgBtzL.js.map +1 -0
  14. package/package.json +48 -15
  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
@@ -1,1201 +0,0 @@
1
- // Configuração do ambiente Node.js com JSDOM + Canvas
2
- import { JSDOM } from 'jsdom';
3
- import { createCanvas, loadImage } from 'canvas';
4
- import JsBarcode from "jsbarcode";
5
- import VariableManager from "../../variableManager.js";
6
-
7
- // Importações para geração de tabelas em PDF
8
- import autoTable from 'jspdf-autotable';
9
-
10
- //import React from 'react';
11
- //import {renderToStaticMarkup} from 'react-dom/server'
12
-
13
- import { getImagesFromUrl, getImagesFromUrlToBase64, mmToPx, convertSVGTableToAutoTableData, generateTableSVG } from "./utils.js";
14
- import { dataTypeList, getInputsByCategory } from "./sortFunctions.js";
15
-
16
- // Configuração do ambiente DOM para Node.js
17
- const dom = new JSDOM('<!DOCTYPE html><html><body><div id="label-container"></div></body></html>');
18
- global.window = dom.window;
19
- global.document = dom.window.document;
20
- global.Image = dom.window.Image;
21
- global.btoa = (str) => Buffer.from(str, 'binary').toString('base64');
22
- global.XMLSerializer = dom.window.XMLSerializer;
23
-
24
- // Variáveis globais para controle
25
- global.stopCreatingLabels = false;
26
- const DEFAULT_LAMINATION_COLORS = {
27
- NO_MATERIAL: "black",
28
- MATERIAL_NOT_MATCHED: "#FF0000",
29
- MATERIAL_MATCHED: "#0f45d8",
30
- }
31
- function getNode(n, v) {
32
- n = document.createElementNS("http://www.w3.org/2000/svg", n);
33
- for (var p in v)
34
- n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);
35
- return n
36
- }
37
- const getAspectRatio = (image, canvas) => {
38
-
39
- const limit = {
40
- w:canvas.width / image.width ,
41
- h: canvas.height / image.height
42
- }
43
- return {
44
- get ratio(){
45
- return limit.w < limit.h ? limit.w : limit.h
46
- },
47
-
48
- }
49
- }
50
-
51
- // **2.**
52
- const createMiniSheet = (sheet, index) => new Promise((resolve, reject) => {
53
- const {parts, vHeight, vWidth} = sheet;
54
- const svgWidth = mmToPx(vHeight);
55
- const svgHeight = mmToPx(vWidth);
56
- const scale = {
57
- width: ((svgHeight - 5) / 275)
58
- };
59
-
60
- const svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
61
- svgElement.id = 'miniSheet-' + index;
62
- svgElement.style.width = svgWidth;
63
- svgElement.style.height = svgHeight;
64
- svgElement.style.transform = 'scaleX(1)';
65
-
66
- const sheetBorder = 3;
67
- const svgRect = getNode('rect', {
68
- x: 0,
69
- y: 0,
70
- width: svgHeight,
71
- height: svgWidth,
72
- stroke: 'black',
73
- strokeWidth: '2px',
74
- fill: 'white',
75
- });
76
- svgElement.appendChild(svgRect);
77
-
78
- const sheetRect = getNode('rect', {
79
- x: sheetBorder,
80
- y: sheetBorder,
81
- width: sheet.height * scale.width,
82
- height: sheet.width * scale.width,
83
- stroke: 'black',
84
- strokeWidth: '2px',
85
- strokeDasharray: "4 1",
86
- fill: 'white',
87
- });
88
- svgElement.appendChild(sheetRect);
89
-
90
- for (const part of parts) {
91
- const rect = getNode('rect', {
92
- y: part.y * scale.width + sheetBorder,
93
- x: part.x * scale.width + sheetBorder,
94
- height: part.width * scale.width,
95
- width: part.height * scale.width,
96
- stroke: 'black',
97
- fill: 'white',
98
- id: part.code,
99
- });
100
- svgElement.appendChild(rect);
101
- }
102
-
103
- // Usar canvas nativo em vez de DOM
104
- const canvas = createCanvas(svgHeight, svgWidth);
105
- canvas.id = 'miniSheetCanvas-' + index;
106
-
107
- const labelContainer = document.getElementById("label-container");
108
-
109
- // Adicionar elementos ao container e resolver imediatamente
110
- labelContainer.appendChild(svgElement);
111
-
112
- // Simular o canvas no DOM para compatibilidade
113
- const canvasElement = document.createElement('canvas');
114
- canvasElement.id = 'miniSheetCanvas-' + index;
115
- canvasElement.width = svgHeight;
116
- canvasElement.height = svgWidth;
117
- labelContainer.appendChild(canvasElement);
118
-
119
- // Armazenar o canvas nativo para uso posterior
120
- canvasElement._nativeCanvas = canvas;
121
-
122
- resolve();
123
- });
124
- const createImage = async (domElement, canvasElement) => {
125
- try {
126
- // Usar canvas nativo se disponível
127
- const canvas = canvasElement._nativeCanvas || createCanvas(canvasElement.width, canvasElement.height);
128
- const ctx = canvas.getContext('2d');
129
-
130
- // Serializar SVG
131
- const xml = new XMLSerializer().serializeToString(domElement);
132
- const svg64 = btoa(xml);
133
- const b64Start = 'data:image/svg+xml;base64,';
134
- const image64 = b64Start + svg64;
135
-
136
- // Usar loadImage do canvas para carregar a imagem
137
- const img = await loadImage(image64);
138
-
139
- // Desenhar no canvas
140
- ctx.drawImage(img, 0, 0);
141
-
142
- return canvas.toDataURL();
143
- } catch (error) {
144
- console.error('Erro ao criar imagem:', error);
145
- throw error;
146
- }
147
- };
148
-
149
-
150
- const createImageFromPart = async (domElement, canvasElement) => {
151
- try {
152
- // Usar canvas nativo se disponível
153
- const canvas = canvasElement._nativeCanvas || createCanvas(canvasElement.width, canvasElement.height);
154
- const ctx = canvas.getContext('2d');
155
-
156
- // Serializar SVG
157
- const xml = new XMLSerializer().serializeToString(domElement);
158
- const svg64 = btoa(xml);
159
- const b64Start = 'data:image/svg+xml;base64,';
160
- const image64 = b64Start + svg64;
161
-
162
- // Usar loadImage do canvas para carregar a imagem
163
- const img = await loadImage(image64);
164
-
165
- // Calcular aspect ratio
166
- const { ratio } = getAspectRatio(img, canvas);
167
-
168
- const specs = {
169
- height: img.height * ratio - 2,
170
- width: img.width * ratio - 2,
171
- };
172
-
173
- let x = (canvas.width / 2) - (specs.width / 2);
174
- let y = (canvas.height / 2) - (specs.height / 2);
175
-
176
- ctx.translate(x, y);
177
- ctx.drawImage(img, 0, 0, specs.width, specs.height);
178
-
179
- return canvas.toDataURL();
180
- } catch (error) {
181
- console.error('Erro ao criar imagem da parte:', error);
182
- throw error;
183
- }
184
- };
185
-
186
- const drawRect = (
187
- pdf,
188
- x,
189
- y,
190
- width,
191
- height,
192
- leftBorderColor,
193
- rightBorderColor,
194
- bottomBorderColor,
195
- topBorderColor
196
- ) => {
197
- const lineDash = [1, 1];
198
- pdf.setLineWidth(0.5);
199
-
200
- setBorder(pdf, x, y, x, height + y, leftBorderColor);
201
- setBorder(pdf, width + x, y, width + x, height + y, rightBorderColor);
202
- setBorder(pdf, x, height + y, width + x, height + y, bottomBorderColor);
203
- setBorder(pdf, x, y, width + x, y, topBorderColor);
204
-
205
- pdf.setLineDash();
206
- };
207
-
208
- const setBorder = (pdf, startX, startY, endX, endY, color) => {
209
- pdf.setDrawColor(color);
210
- if (color === DEFAULT_LAMINATION_COLORS.NO_MATERIAL) {
211
- pdf.setLineDash([1, 1]);
212
- } else {
213
- pdf.setLineDash();
214
- }
215
- pdf.line(startX, startY, endX, endY);
216
- };
217
- const makeVariable = (mainObject) => {
218
- const {
219
- width,
220
- height,
221
- y,
222
- x,
223
- vLeft,
224
- verticalSpace,
225
- marginLeft,
226
- vTop,
227
- horizontalSpace,
228
- marginTop,
229
- vHeight,
230
- pdfInstance,
231
- v,
232
- inputs,
233
- outputs,
234
- } = mainObject;
235
-
236
- let vpx = width * y + vLeft + verticalSpace * y + marginLeft;
237
- let vpy = height * x + vTop + horizontalSpace * x + marginTop;
238
-
239
- if (v.angle === 90) {
240
- vpx = width * y + vLeft + verticalSpace * y - vHeight + marginLeft;
241
- vpy = height * x + vTop + horizontalSpace * x + marginTop;
242
- }
243
-
244
- pdfInstance.setFontSize(v.fontSize * 0.75);
245
- pdfInstance.setFont(undefined, v.fontWeight || 'normal');
246
-
247
- // Usa o método performReplacement do VariableManager
248
- const variableManager = new VariableManager();
249
- const processedText = variableManager.performReplacement(inputs, outputs, v.text);
250
-
251
- pdfInstance.text(
252
- processedText,
253
- vpx,
254
- vpy,
255
- null,
256
- v.angle * -1,
257
- v.textAlign || "left"
258
- );
259
- };
260
- const makeRect = (mainObject) => {
261
- const {
262
- pdfInstance,
263
- width,
264
- y,
265
- x,
266
- verticalSpace,
267
- horizontalSpace,
268
- marginTop,
269
- marginLeft,
270
- vLeft,
271
- vTop,
272
- vWidth,
273
- vHeight,
274
- height,
275
- color = "black",
276
- } = mainObject;
277
- pdfInstance.setLineWidth(0.5);
278
- pdfInstance.setDrawColor(color);
279
- pdfInstance.rect(
280
- width * y + (verticalSpace * y + marginLeft) + vLeft,
281
- height * x + (horizontalSpace * x + marginTop) + vTop,
282
- vWidth,
283
- vHeight,
284
- "S"
285
- );
286
- };
287
- const makeText = (mainObject) => {
288
- const {
289
- pdfInstance,
290
- v,
291
- width,
292
- y,
293
- x,
294
- verticalSpace,
295
- marginLeft,
296
- marginTop,
297
- vLeft,
298
- vTop,
299
- horizontalSpace,
300
- height,
301
- } = mainObject;
302
- pdfInstance.setFontSize(v.fontSize * 0.75);
303
- pdfInstance.setFont(undefined, v.fontWeight || 'normal');
304
- pdfInstance.text(
305
- v.text,
306
- width * y + (verticalSpace * y + marginLeft) + vLeft,
307
- height * x + (horizontalSpace * x + marginTop) + vTop,
308
- null,
309
- v.angle
310
- );
311
- };
312
- const makeImage = async (mainObject) => {
313
- const {
314
- width,
315
- height,
316
- vWidth,
317
- vHeight,
318
- horizontalSpace,
319
- verticalSpace,
320
- y,
321
- marginTop,
322
- marginLeft,
323
- vLeft,
324
- vTop,
325
- pdfInstance,
326
- x,
327
- v,
328
- imagesCache,
329
- } = mainObject;
330
- if (!imagesCache[v.src]) {
331
- await getImagesFromUrlToBase64(v.src)
332
- .then((data) => {
333
- imagesCache[v.src] = data;
334
- })
335
- .catch((error) => {
336
- console.error("Error loading image:", error);
337
- imagesCache[v.src] = null;
338
- });
339
- }
340
-
341
- // Verifica se temos uma imagem válida no cache
342
- if (!imagesCache[v.src]) {
343
- console.warn(`Image not available: ${v.src}`);
344
- return;
345
- }
346
-
347
- try {
348
- // Determina o formato da imagem baseado nos dados
349
- const imageData = imagesCache[v.src];
350
- let format = "JPEG";
351
-
352
- if (typeof imageData === 'string') {
353
- if (imageData.indexOf('data:image/png') === 0) format = "PNG";
354
- else if (imageData.indexOf('data:image/gif') === 0) format = "GIF";
355
- }
356
-
357
- pdfInstance.addImage(
358
- imageData,
359
- format,
360
- width * y + (verticalSpace * y + marginLeft) + vLeft,
361
- height * x + (horizontalSpace * x + marginTop) + vTop,
362
- vWidth,
363
- vHeight
364
- );
365
- } catch (error) {
366
- console.error("Error adding image to PDF:", error);
367
- }
368
- };
369
- const makeBarCode = (mainObject) => {
370
- const {
371
- v,
372
- width,
373
- verticalSpace,
374
- horizontalSpace,
375
- vHeight,
376
- vLeft,
377
- vWidth,
378
- vTop,
379
- marginLeft,
380
- marginTop,
381
- height,
382
- x,
383
- y,
384
- pdfInstance,
385
- vl,
386
- inputs,
387
- outputs,
388
- } = mainObject;
389
- const codeASD = vl.code_a ? `0${vl.code_a.substr(1)}` : null;
390
- const codeBSD = vl.code_b ? `0${vl.code_b.substr(1)}` : null;
391
- const getCustomVars = (text) =>
392
- text
393
- .replace("{{FURO_A}}", vl.code_a || null)
394
- .replace("{{FURO_B}}", vl.code_b || null)
395
- .replace("{{FURO_A2}}", vl.code_a2 || null)
396
- .replace("{{FURO_B2}}", vl.code_b2 || null)
397
- .replace("{{PROJETO_ID}}", vl.project_id || null)
398
- .replace("{{LOTE_ID}}", vl.group_id || null)
399
- .replace("{{PECA_CODIGO}}", vl.pid || null)
400
- .replace("{{MODULO_REF}}", vl.mref || null)
401
- .replace("{{PECA_REF}}", vl.pref || null)
402
- .replace("{{FURO_A_SD}}", codeASD || null)
403
- .replace("{{FURO_B_SD}}", codeBSD || null)
404
- .replace("{{FURO_TOPO}}", vl.code_top || null); //furo topo;
405
-
406
- let bar =
407
- v.originBarcode === "PERSONALIZADO"
408
- ? getCustomVars(v.customBarcode) || "null"
409
- : (() => {
410
- const variableManager = new VariableManager();
411
- return variableManager.performReplacement(inputs, outputs, v.originBarcode);
412
- })();
413
- if (!bar.includes("null") && bar.length > 0) {
414
- // Usar canvas nativo em vez de DOM
415
- let canvas = createCanvas(400, 200);
416
- let px = width * y + (verticalSpace * y + marginLeft) + vLeft;
417
- let py = height * x + (horizontalSpace * x + marginTop) + vTop;
418
-
419
- try {
420
- JsBarcode(canvas, bar);
421
- } catch (error) {
422
- console.error('Erro ao gerar código de barras:', error);
423
- // Usar canvas vazio em caso de erro
424
- canvas = createCanvas(400, 200);
425
- }
426
-
427
- if (v.angle === 90) {
428
- px = width * y + (verticalSpace * y + marginLeft) + vLeft - vHeight;
429
- py = height * x + (horizontalSpace * x + marginTop) + vTop - vHeight;
430
- } else if (v.angle === 270) {
431
- px = width * y + (verticalSpace * y + marginLeft) + vLeft + vHeight;
432
- py = height * x + (horizontalSpace * x + marginTop) + vTop - vHeight;
433
- } else if (v.angle === 180) {
434
- px = width * y + (verticalSpace * y + marginLeft) + vLeft;
435
- py = height * x + (horizontalSpace * x + marginTop) + vTop - vWidth;
436
- }
437
-
438
- pdfInstance.addImage(
439
- canvas.toDataURL(),
440
- "PNG",
441
- px,
442
- py,
443
- vWidth,
444
- vHeight,
445
- null,
446
- null,
447
- v.angle * -1
448
- );
449
- }
450
- };
451
-
452
- const makeLamination = (mainObject) => {
453
- const {
454
- width,
455
- height,
456
- x,
457
- y,
458
- verticalSpace,
459
- horizontalSpace,
460
- marginTop,
461
- marginLeft,
462
- vLeft,
463
- vTop,
464
- pdfInstance,
465
- vHeight,
466
- vWidth,
467
- partList,
468
- indexLabel,
469
- v,
470
- vl,
471
- actualData,
472
- } = mainObject;
473
- const borderColor = {
474
- left: vl.edge_left_id !== "0" ? (vl.edge_left_id === vl.material_id ? DEFAULT_LAMINATION_COLORS.MATERIAL_MATCHED : DEFAULT_LAMINATION_COLORS.MATERIAL_NOT_MATCHED) : DEFAULT_LAMINATION_COLORS.NO_MATERIAL,
475
- right: vl.edge_right_id !== "0" ? (vl.edge_right_id === vl.material_id ? DEFAULT_LAMINATION_COLORS.MATERIAL_MATCHED : DEFAULT_LAMINATION_COLORS.MATERIAL_NOT_MATCHED) : DEFAULT_LAMINATION_COLORS.NO_MATERIAL,
476
- bottom: vl.edge_bottom_id !== "0" ? (vl.edge_bottom_id === vl.material_id ? DEFAULT_LAMINATION_COLORS.MATERIAL_MATCHED : DEFAULT_LAMINATION_COLORS.MATERIAL_NOT_MATCHED) : DEFAULT_LAMINATION_COLORS.NO_MATERIAL,
477
- top: vl.edge_top_id !== "0" ? (vl.edge_top_id === vl.material_id ? DEFAULT_LAMINATION_COLORS.MATERIAL_MATCHED : DEFAULT_LAMINATION_COLORS.MATERIAL_NOT_MATCHED) : DEFAULT_LAMINATION_COLORS.NO_MATERIAL,
478
- };
479
-
480
- const px = width * y + (verticalSpace * y + marginLeft) + vLeft;
481
- const py = height * x + (horizontalSpace * x + marginTop) + vTop;
482
- drawRect(pdfInstance, px, py, vWidth, vHeight, borderColor.left, borderColor.right, borderColor.bottom, borderColor.top);
483
-
484
- if (v.showEdges) {
485
- pdfInstance.setFontSize(7);
486
- pdfInstance.text(actualData["edge_left"] || "", px - 2, py + vHeight, null, 90, "left");
487
- pdfInstance.text(actualData["edge_right"] || "", px + vWidth + 2, py, null, -90, "left");
488
- pdfInstance.text(actualData["edge_top"] || "", px, py - 2, null, 0, "left");
489
- pdfInstance.text(actualData["edge_bottom"] || "", px + vWidth, py + vHeight + 2, null, 180, "left");
490
- }
491
- };
492
-
493
-
494
- async function makeMiniSheet(mainObject) {
495
-
496
- const {
497
- pdfInstance,
498
- partIndex,
499
- width,
500
- height,
501
- vHeight,
502
- vWidth,
503
- x,
504
- y,
505
- verticalSpace,
506
- horizontalSpace,
507
- marginLeft,
508
- marginTop,
509
- vLeft,
510
- vTop,
511
- sheets,
512
- actualData,
513
- nextData,
514
- userPrefs,
515
- sheetsByPartCode,
516
- } = mainObject;
517
- if (!global.stopCreatingLabels) {
518
- const sheetIndex = sheetsByPartCode[actualData.index];
519
- this.actualSheet = sheets[sheetIndex];
520
- if(this.index !== sheetIndex){
521
- this.index = sheetIndex;
522
- await createMiniSheet({...this.actualSheet,vHeight,vWidth},sheetIndex)
523
-
524
- }
525
-
526
- // Buscar elementos usando JSDOM em vez de DOM
527
- const miniSheetElement = document.querySelector(`#miniSheet-${sheetIndex}`);
528
- const actualRect = document.getElementById(actualData.index);
529
-
530
- if (actualRect && actualRect.style) {
531
- actualRect.style.fill = 'black';
532
- }
533
- const miniSheetCanvasElement = document.querySelector(`#miniSheetCanvas-${sheetIndex}`);
534
-
535
- let px = width * y + (verticalSpace * y + marginLeft) + vLeft;
536
- let py = height * x + (horizontalSpace * x + marginTop) + vTop;
537
-
538
- if (mainObject.v.angle === 90) {
539
- px = width * y + (verticalSpace * y + marginLeft) + vLeft - vHeight;
540
- py = height * x + (horizontalSpace * x + marginTop) + vTop - vHeight;
541
- } else if (mainObject.v.angle === 270) {
542
- px = width * y + (verticalSpace * y + marginLeft) + vLeft + vHeight;
543
- py = height * x + (horizontalSpace * x + marginTop) + vTop - vHeight;
544
- } else if (mainObject.v.angle === 180) {
545
- px = width * y + (verticalSpace * y + marginLeft) + vLeft;
546
- py = height * x + (horizontalSpace * x + marginTop) + vTop + -(height ) ;
547
-
548
- }
549
-
550
- if (miniSheetElement && miniSheetCanvasElement) {
551
- const png = await createImage(miniSheetElement,miniSheetCanvasElement);
552
-
553
- if (actualRect && actualRect.style) {
554
- actualRect.style.fill = 'white';
555
- }
556
-
557
- pdfInstance.addImage(
558
- png,
559
- "PNG",
560
- px,
561
- py,
562
- vWidth,
563
- vHeight,
564
- null,
565
- 'NONE',
566
- mainObject.v.angle * -1
567
- );
568
-
569
- if(!nextData){
570
- this.index = null;
571
- if (miniSheetElement && miniSheetElement.remove) {
572
- miniSheetElement.remove();
573
- }
574
- if (miniSheetCanvasElement && miniSheetCanvasElement.remove) {
575
- miniSheetCanvasElement.remove();
576
- }
577
- }
578
- }
579
- }else{
580
- try{
581
- const sheetIndex = sheetsByPartCode[actualData.index];
582
- const miniSheetElement = document.querySelector(`#miniSheet-${sheetIndex}`);
583
- const miniSheetCanvasElement = document.querySelector(`#miniSheetCanvas-${sheetIndex}`);
584
-
585
- if (miniSheetElement && miniSheetElement.remove) {
586
- miniSheetElement.remove();
587
- }
588
- if (miniSheetCanvasElement && miniSheetCanvasElement.remove) {
589
- miniSheetCanvasElement.remove();
590
- }
591
- global.stopCreatingLabels = false;
592
- }catch{
593
- return ;
594
- }
595
-
596
- }
597
-
598
- return;
599
- };
600
- const getMiniPartElement = (prefix, variable) => {
601
- // Buscar em elementos mock em vez de DOM
602
- const mockElements = global.mockElements || [];
603
- return mockElements.find(el => el.id === `${prefix}-${variable}`);
604
- };
605
-
606
- export const createSvgPart = ({ width, height, ...part }) => {
607
- let factor = 0.05;
608
-
609
- const realMeasures = {
610
- height : width * factor > 10 ? width * factor : 10,
611
- width : height * factor > 10 ? height * factor : 10
612
- }
613
- const container = getNode('svg', {
614
- width: realMeasures.width+2,
615
- height: realMeasures.height+2,
616
- id: `svg-${part.code}`,
617
- class:"partRemove"
618
- });
619
-
620
- // Usar canvas nativo em vez de DOM
621
- const canvas = createCanvas(part.canvasWidth * 3.77, part.canvasHeight * 3.77);
622
- canvas.id = `canvas-${part.code}`;
623
- canvas.classList = { add: () => {} }; // Mock classList
624
- const ctx = canvas.getContext('2d');
625
- ctx.strokeStyle = "#FF0000";
626
-
627
- const partRect = getNode('rect', {
628
- x: 1,
629
- y: 1,
630
- width: realMeasures.width ,
631
- height: realMeasures.height,
632
- stroke: '#000000',
633
- strokeWidth: '2px',
634
- fill: 'white',
635
- });
636
- container.appendChild(partRect);
637
-
638
- // Adicionar aos elementos mock em vez de document.body
639
- global.mockElements = global.mockElements || [];
640
- global.mockElements.push(container, canvas);
641
- };
642
- const makeMiniPart = async ({vl:part,
643
- side,
644
- ...rest}) => {
645
- const { vHeight,
646
- vWidth,
647
- x,
648
- y,
649
- verticalSpace,
650
- horizontalSpace,
651
- marginLeft,
652
- marginTop,
653
- vLeft,
654
- vTop,
655
- pdfInstance} = rest;
656
- let px = rest.width * y + (verticalSpace * y + marginLeft) + vLeft;
657
- let py = rest.height * x + (horizontalSpace * x + marginTop) + vTop;
658
-
659
- if (rest.v.angle === 90) {
660
- px = rest.width * y + (verticalSpace * y + marginLeft) + vLeft - vHeight;
661
- py = rest.height * x + (horizontalSpace * x + marginTop) + vTop - vHeight;
662
- } else if (rest.v.angle === 270) {
663
- px = rest.width * y + (verticalSpace * y + marginLeft) + vLeft + vHeight;
664
- py = rest.height * x + (horizontalSpace * x + marginTop) + vTop - vHeight;
665
- } else if (rest.v.angle === 180) {
666
- px = rest.width * y + (verticalSpace * y + marginLeft) + vLeft;
667
- py = rest.height * x + (horizontalSpace * x + marginTop) + vTop + -( rest.height ) ;
668
-
669
- }
670
- const code = part.index.replace('.','-') + '-' + side
671
- createSvgPart({...part,code:code,canvasWidth:vWidth,canvasHeight:vHeight})
672
- const svgElement = getMiniPartElement('svg',code)
673
- const canvasElement = getMiniPartElement('canvas',code)
674
- const png = await createImageFromPart(svgElement,canvasElement);
675
- pdfInstance.addImage(
676
- png,
677
- "JPG",
678
- px,
679
- py,
680
- vWidth,
681
- vHeight,
682
- null,
683
- 'NONE',
684
- rest.v.angle * -1
685
-
686
-
687
- );
688
-
689
- }
690
-
691
- const additionalProps = {
692
- index:null
693
- };
694
-
695
- const resetCharSpace = (doc) => {
696
- /*
697
- Essa função foi feita para resetar o charSpace.
698
- Quando o charSpace é definido em um texto, ele é definido globalmente logo todos os textos ficam com o mesmo charSpace, gerando diversas inconsistências no documento.
699
- Isso é um problema do jsPDF que não foi resolvido na versão atual.
700
- Issue: https://github.com/parallax/jsPDF/issues/1575
701
- */
702
- doc.text(
703
- " ",
704
- -1,
705
- -1 ,
706
- {charSpace: 0 },
707
-
708
- );
709
- }
710
- const makeIdentifierByProject = async (mainObject) => {
711
- try {
712
- const {
713
- pdfInstance,
714
- width,
715
- y,
716
- x,
717
- verticalSpace,
718
- horizontalSpace,
719
- marginTop,
720
- marginLeft,
721
- vLeft,
722
- vTop,
723
- vWidth,
724
- vHeight,
725
- height,
726
- v,
727
- numberByProject,
728
- hasColor,
729
- actualData: { project_id }
730
- } = mainObject;
731
-
732
- // Validate required parameters
733
- if (!pdfInstance || !project_id || vWidth <= 0 || vHeight <= 0) {
734
- console.warn('Invalid parameters for makeIdentifierByProject', {
735
- hasPdf: !!pdfInstance,
736
- project_id,
737
- vWidth,
738
- vHeight
739
- });
740
- return;
741
- }
742
-
743
- // Safely get number/color from numberByProject
744
- const projectData = (global.numberByProject || new Map()).get(project_id);
745
- if (!projectData) {
746
- console.warn(`No data found for project_id: ${project_id}`);
747
- return;
748
- }
749
-
750
- const { number, color } = projectData;
751
- const currentColor = hasColor && color ? color : 'black';
752
-
753
- // Draw rectangle first
754
- makeRect({ ...mainObject, color: currentColor });
755
-
756
- // Text rendering function with safety checks
757
- const renderText = (text) => {
758
- if (!text) {
759
- console.warn('No text provided to render');
760
- return;
761
- }
762
-
763
- // Calculate initial fontSize with a minimum size
764
- let fontSize = Math.max(vHeight * 3.2, 1);
765
- pdfInstance.setFontSize(fontSize);
766
- pdfInstance.setFont(undefined, 'bold');
767
-
768
- // Get text dimensions with error handling
769
- let textDimensions;
770
- try {
771
- textDimensions = pdfInstance.getTextDimensions(text);
772
- } catch (error) {
773
- console.error('Error getting text dimensions:', error);
774
- return;
775
- }
776
-
777
- // Adjust font size if text is too wide
778
- if (textDimensions.w > vWidth) {
779
- const scaleFactor = vWidth / textDimensions.w;
780
- fontSize = Math.max((fontSize * scaleFactor) - 1, 1); // Ensure minimum font size
781
- pdfInstance.setFontSize(fontSize);
782
- textDimensions = pdfInstance.getTextDimensions(text);
783
- }
784
-
785
- // Calculate position with safety checks
786
- const xPos = width * y + (verticalSpace * y + marginLeft) + vLeft +
787
- (vHeight / 2) - (textDimensions.w / 2);
788
- const yPos = height * x + (horizontalSpace * x + marginTop) + vTop +
789
- vHeight / 1.1;
790
-
791
- // Set colors and render text
792
- try {
793
- pdfInstance.setTextColor(currentColor);
794
- pdfInstance.text(
795
- text,
796
- Math.max(xPos, 0), // Ensure positive coordinates
797
- Math.max(yPos, 0),
798
- {
799
- charSpace: "-0.5",
800
- angle: v?.angle || 0
801
- }
802
- );
803
- } catch (error) {
804
- console.error('Error rendering text:', error);
805
- }
806
-
807
- // Safe reset of charSpace
808
- try {
809
- pdfInstance.text(" ", 0, 0, { charSpace: 0 });
810
- } catch (error) {
811
- console.error('Error resetting charSpace:', error);
812
- }
813
- };
814
-
815
- // Render the number with error handling
816
- if (number !== undefined && number !== null) {
817
- renderText(`${number}`);
818
- } else {
819
- console.warn('Invalid number value:', number);
820
- }
821
-
822
- // Reset colors
823
- pdfInstance.setDrawColor('black');
824
- pdfInstance.setTextColor('black');
825
-
826
- } catch (error) {
827
- console.error('Error in makeIdentifierByProject:', error);
828
- // Optionally rethrow or handle error
829
- }
830
- };
831
-
832
-
833
- const makeEnhancedLamination = (mainObject) => {
834
- const {
835
- width,
836
- height,
837
- x,
838
- y,
839
- verticalSpace,
840
- horizontalSpace,
841
- marginTop,
842
- marginLeft,
843
- vLeft,
844
- vTop,
845
- pdfInstance,
846
- vHeight,
847
- vWidth,
848
- vl,
849
- } = mainObject;
850
-
851
- // Define colors for different lamination states
852
- const borderColor = {
853
- left: vl.edge_left_id !== "0" ?
854
- (vl.edge_left_id === vl.material_id ? DEFAULT_LAMINATION_COLORS.MATERIAL_MATCHED : DEFAULT_LAMINATION_COLORS.MATERIAL_NOT_MATCHED)
855
- : DEFAULT_LAMINATION_COLORS.NO_MATERIAL,
856
- right: vl.edge_right_id !== "0" ?
857
- (vl.edge_right_id === vl.material_id ? DEFAULT_LAMINATION_COLORS.MATERIAL_MATCHED : DEFAULT_LAMINATION_COLORS.MATERIAL_NOT_MATCHED)
858
- : DEFAULT_LAMINATION_COLORS.NO_MATERIAL,
859
- bottom: vl.edge_bottom_id !== "0" ?
860
- (vl.edge_bottom_id === vl.material_id ? DEFAULT_LAMINATION_COLORS.MATERIAL_MATCHED : DEFAULT_LAMINATION_COLORS.MATERIAL_NOT_MATCHED)
861
- : DEFAULT_LAMINATION_COLORS.NO_MATERIAL,
862
- top: vl.edge_top_id !== "0" ?
863
- (vl.edge_top_id === vl.material_id ? DEFAULT_LAMINATION_COLORS.MATERIAL_MATCHED : DEFAULT_LAMINATION_COLORS.MATERIAL_NOT_MATCHED)
864
- : DEFAULT_LAMINATION_COLORS.NO_MATERIAL,
865
- };
866
-
867
- // Calculate base position
868
- const px = width * y + (verticalSpace * y + marginLeft) + vLeft;
869
- const py = height * x + (horizontalSpace * x + marginTop) + vTop;
870
-
871
- // Draw outer rectangle
872
- pdfInstance.setDrawColor('black');
873
- pdfInstance.setLineWidth(0.5);
874
- pdfInstance.rect(px, py, vWidth, vHeight, 'S');
875
-
876
- // Calculate scale based on piece dimensions
877
- const pieceWidth = vl.width;
878
- const pieceHeight = vl.height;
879
- const aspectRatio = pieceWidth / pieceHeight;
880
-
881
- // Calculate scaled dimensions to fit within the container
882
- const maxInnerWidth = vWidth * 0.7;
883
- const maxInnerHeight = vHeight * 0.7;
884
-
885
- let innerWidth, innerHeight;
886
- if (aspectRatio > 1) {
887
- innerWidth = maxInnerWidth;
888
- innerHeight = innerWidth / aspectRatio;
889
- if (innerHeight > maxInnerHeight) {
890
- innerHeight = maxInnerHeight;
891
- innerWidth = innerHeight * aspectRatio;
892
- }
893
- } else {
894
- innerHeight = maxInnerHeight;
895
- innerWidth = innerHeight * aspectRatio;
896
- if (innerWidth > maxInnerWidth) {
897
- innerWidth = maxInnerWidth;
898
- innerHeight = innerWidth / aspectRatio;
899
- }
900
- }
901
-
902
- // Calculate padding to center the inner rectangle
903
- const paddingX = (vWidth - innerWidth) / 2;
904
- const paddingY = (vHeight - innerHeight) / 2;
905
-
906
- // Draw inner rectangle with lamination borders
907
- drawRect(
908
- pdfInstance,
909
- px + paddingX,
910
- py + paddingY,
911
- innerWidth,
912
- innerHeight,
913
- borderColor.left,
914
- borderColor.right,
915
- borderColor.bottom,
916
- borderColor.top
917
- );
918
-
919
- // Calculate scale factor for converting measurements
920
- const scaleFactor = innerWidth / pieceWidth;
921
- // Draw holes and cuts if they exist
922
- if (vl.holes_diagram && Array.isArray(vl.holes_diagram)) {
923
- vl.holes_diagram.forEach((hole, index) => {
924
- pdfInstance.setLineWidth(0.5);
925
-
926
- // Helper function to scale coordinates
927
- const scaleCoord = (coord) => (coord / 10) * scaleFactor;
928
-
929
- if (hole.type === "circle") {
930
- const centerX = px + paddingX + (hole.rotated ?
931
- (pieceHeight - (hole.py / 10)) * scaleFactor :
932
- scaleCoord(hole.px));
933
- const centerY = py + paddingY + (hole.rotated ?
934
- scaleCoord(hole.px) :
935
- scaleCoord(hole.py));
936
- const radius = (hole.di / 25) * scaleFactor;
937
-
938
- pdfInstance.setDrawColor('#FF0000');
939
- pdfInstance.circle(centerX, centerY, radius, 'F');
940
- }
941
- else if (hole.type === "line") {
942
- const lineCoords = {
943
- x1: hole.rotated ? scaleCoord(hole.x1) : pieceHeight - scaleCoord(hole.py),
944
- y1: hole.rotated ? scaleCoord(hole.py) : scaleCoord(hole.x1),
945
- x2: hole.rotated ? scaleCoord(hole.x2) : pieceHeight - scaleCoord(hole.py),
946
- y2: hole.rotated ? scaleCoord(hole.py) : scaleCoord(hole.x2),
947
- };
948
-
949
- pdfInstance.setDrawColor('#00FF00');
950
- pdfInstance.setLineWidth((hole.di || 1) * scaleFactor / 25);
951
- pdfInstance.line(
952
- px + paddingX + lineCoords.x1,
953
- py + paddingY + lineCoords.y1,
954
- px + paddingX + lineCoords.x2,
955
- py + paddingY + lineCoords.y2
956
- );
957
- }
958
- else if (hole.type === "polyline") {
959
- pdfInstance.setDrawColor('#FF0000');
960
- pdfInstance.setLineWidth((hole.di || 1) * scaleFactor / 25);
961
-
962
- // Draw polyline segments
963
- for (let i = 0; i < hole.steps.length - 1; i++) {
964
- const current = hole.steps[i];
965
- const next = hole.steps[i + 1];
966
-
967
- const x1 = px + paddingX + (hole.rotated ?
968
- scaleCoord(current.y) :
969
- pieceHeight - scaleCoord(current.x));
970
- const y1 = py + paddingY + (hole.rotated ?
971
- scaleCoord(current.x) :
972
- scaleCoord(current.y));
973
- const x2 = px + paddingX + (hole.rotated ?
974
- scaleCoord(next.y) :
975
- pieceHeight - scaleCoord(next.x));
976
- const y2 = py + paddingY + (hole.rotated ?
977
- scaleCoord(next.x) :
978
- scaleCoord(next.y));
979
-
980
- pdfInstance.line(x1, y1, x2, y2);
981
- }
982
-
983
- // Draw circle at polyline start
984
- if (hole.px !== undefined && hole.py !== undefined) {
985
- const circleX = px + paddingX + (hole.rotated ?
986
- scaleCoord(hole.py) :
987
- scaleCoord(hole.px));
988
- const circleY = py + paddingY + (hole.rotated ?
989
- scaleCoord(hole.px) :
990
- scaleCoord(hole.py));
991
- const radius = (hole.di / 25) * scaleFactor;
992
-
993
- pdfInstance.setFillColor(0, 0, 0);
994
- pdfInstance.circle(circleX, circleY, radius, 'F');
995
- }
996
- }
997
- });
998
- }
999
-
1000
- // Draw black square indicator (10% of the height in the bottom right corner)
1001
- const squareSize = vHeight * 0.1;
1002
- const squareMargin = vHeight * 0.05;
1003
-
1004
- pdfInstance.setFillColor(0, 0, 0);
1005
- pdfInstance.rect(
1006
- px + vWidth - squareSize - squareMargin,
1007
- py + vHeight - squareSize - squareMargin,
1008
- squareSize,
1009
- squareSize,
1010
- 'F'
1011
- );
1012
-
1013
- // Add dimension labels
1014
- pdfInstance.setFontSize(8);
1015
- pdfInstance.setTextColor(0, 0, 0);
1016
-
1017
- // Width label
1018
- const widthText = `L: ${pieceWidth}mm`;
1019
- const widthTextWidth = pdfInstance.getTextWidth(widthText);
1020
- pdfInstance.text(
1021
- widthText,
1022
- px + (vWidth - widthTextWidth) / 2,
1023
- py + vHeight - squareMargin
1024
- );
1025
-
1026
- // Height label
1027
- const heightText = `A: ${pieceHeight}mm`;
1028
- pdfInstance.text(
1029
- heightText,
1030
- px + vWidth - squareSize - squareMargin * 2,
1031
- py + (vHeight + pdfInstance.getTextWidth(heightText)) / 2,
1032
- { angle: 90 }
1033
- );
1034
-
1035
- // Reset colors and text settings
1036
- pdfInstance.setDrawColor('black');
1037
- pdfInstance.setFillColor('white');
1038
- pdfInstance.setTextColor('black');
1039
- resetCharSpace(pdfInstance);
1040
- };
1041
- export async function insertFiguresToPdf({ specialProp, ...rest }) {
1042
- const insertFigure = {
1043
- rect: () => makeRect(rest),
1044
- identifierByProject: () => makeIdentifierByProject({...rest,hasColor:false,numberByProject:global.numberByProject}),
1045
- colorfulIdentifierByProject: () => makeIdentifierByProject({...rest,hasColor:true,numberByProject:global.numberByProject}),
1046
- enhancedLamination: () => makeLamination(rest) ,
1047
- text: () => makeText(rest),
1048
- Image: () => makeImage(rest),
1049
- barCode: () => makeBarCode(rest),
1050
- lamination: () => makeLamination(rest),
1051
- variable: () => makeVariable(rest),
1052
- miniSheet: () => makeMiniSheet.apply(additionalProps ,[rest]),
1053
- miniPartA: () => makeMiniPart({...rest,side:"sideA"}),
1054
- miniPartB: ()=> makeMiniPart({...rest,side:"sideB"}),
1055
- volumeContent: () => {
1056
- const {
1057
- pdfInstance,
1058
- width,
1059
- height,
1060
- x,
1061
- y,
1062
- verticalSpace,
1063
- horizontalSpace,
1064
- marginTop,
1065
- marginLeft,
1066
- vLeft,
1067
- vTop,
1068
- vWidth,
1069
- v,
1070
- actualData: currentPart,
1071
- inputs,
1072
- outputs
1073
- } = rest;
1074
- // Processar dados usando dataTypeList se necessário
1075
- let processedData = currentPart;
1076
- try {
1077
- // Usar o dataTypeList para processar dados de acordo com o tipo especificado
1078
- const typeProcessedData = dataTypeList('volume', [currentPart]);
1079
- console.log("Dados processados com dataTypeList:", typeProcessedData);
1080
- processedData = {
1081
- ...typeProcessedData[0]
1082
- };
1083
-
1084
- } catch (error) {
1085
- console.error(`Erro ao processar dados com dataTypeList (${v.dataType}):`, error);
1086
- }
1087
-
1088
- console.log("Gerando tabela de volumeContent para:", processedData.itemList);
1089
-
1090
- if (processedData.itemList && Array.isArray(processedData.itemList)) {
1091
- try {
1092
- // Verificar se a tabela de itens contém dados válidos
1093
- if (processedData.itemList.length === 0) {
1094
- console.warn("Lista de itens vazia para volumeContent");
1095
- return;
1096
- }
1097
-
1098
- // Gerar dados da tabela
1099
- const { headers, rows } = convertSVGTableToAutoTableData(processedData.itemList);
1100
- console.log("Gerando tabela de volume: ", headers, "colunas,", rows, "linhas", processedData.itemList);
1101
-
1102
- // Calcular posição inicial da tabela
1103
- const startY = height * x + (horizontalSpace * x + marginTop) + vTop;
1104
- const marginLeft = width * y + (verticalSpace * y + rest.marginLeft) + vLeft + 0.5;
1105
-
1106
- // Verificar se o pdfInstance é válido
1107
- if (!pdfInstance || typeof pdfInstance.addPage !== 'function') {
1108
- console.error("Instância PDF inválida para autoTable");
1109
- return;
1110
- }
1111
-
1112
- // Verificar se autoTable está disponível
1113
- if (typeof autoTable !== 'function') {
1114
- console.error("autoTable não está disponível como função");
1115
- return;
1116
- }
1117
-
1118
-
1119
- // Log de debug para verificar o estado do pdfInstance
1120
- console.log("pdfInstance é válido, aplicando autoTable");
1121
-
1122
- // Gerar a tabela no PDF com tratamento de erros
1123
- try {
1124
- autoTable(pdfInstance, {
1125
- head: [headers], // Cabeçalho
1126
- body: rows, // Linhas
1127
- startY: startY,
1128
- theme: 'grid', // Estilo da tabela
1129
- styles: {
1130
- fontSize: 4,
1131
- cellPadding: 0.5,
1132
- lineHeight: 0.6,
1133
- minCellHeight: 1.8,
1134
- overflow: 'linebreak',
1135
- halign: 'center'
1136
- },
1137
- headStyles: {
1138
- fillColor: [240, 240, 240],
1139
- textColor: [0, 0, 0],
1140
- fontStyle: 'bold',
1141
- minCellHeight: 1.8
1142
- },
1143
- margin: { top: 10, right: 5, bottom: 0, left: marginLeft },
1144
- tableWidth: vWidth,
1145
- rowPageBreak: 'avoid',
1146
- pageBreak: 'auto',
1147
- showHead: 'firstPage',
1148
- didDrawPage: function(data) {
1149
- // Quando nova página for criada, redefine Y mas mantém a mesma margem esquerda
1150
- data.settings.margin.top = 0.5;
1151
- data.cursor.y = 0.5;
1152
- },
1153
- columnStyles: {
1154
- // Definição de larguras específicas para colunas
1155
- 0: { cellWidth: vWidth * 0.15 }, // ID - 15%
1156
- 1: { cellWidth: vWidth * 0.4 }, // Nome - 40%
1157
- 2: { cellWidth: vWidth * 0.1 }, // Qtd - 10%
1158
- 3: { cellWidth: vWidth * 0.35 } // Dimensões - 35%
1159
- }
1160
- });
1161
- } catch (tableError) {
1162
- console.error("Erro ao criar tabela automatizada:", tableError);
1163
-
1164
- // Fallback: Desenhar retângulo simples indicando onde estaria a tabela
1165
- pdfInstance.setDrawColor(0);
1166
- pdfInstance.setLineWidth(0.5);
1167
- pdfInstance.rect(
1168
- marginLeft,
1169
- startY,
1170
- vWidth,
1171
- Math.min(50, rows.length * 5 + 10),
1172
- 'S'
1173
- );
1174
-
1175
- // Adicionar texto indicando problema
1176
- pdfInstance.setFontSize(6);
1177
- pdfInstance.text(
1178
- "Tabela de itens (erro ao renderizar)",
1179
- marginLeft + 2,
1180
- startY + 5
1181
- );
1182
- }
1183
- } catch (error) {
1184
- console.error("Erro ao processar volumeContent:", error);
1185
- }
1186
- } else {
1187
- console.warn("Dados de itemList inválidos ou ausentes para volumeContent");
1188
- }
1189
- },
1190
- };
1191
- console.log(specialProp)
1192
-
1193
- try {
1194
- await insertFigure[specialProp]();
1195
-
1196
- } catch (error) {
1197
- console.error(`Erro específico ao processar ${specialProp}:`, error);
1198
- throw new Error(`Erro durante a criação das etiquetas para ${specialProp}: ${error.message}`);
1199
- }
1200
- return true;
1201
- }