@jtandrelevicius/utils-js-library 1.0.0 → 1.0.1

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 (2) hide show
  1. package/index.js +26 -63
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * DataQueryService
2
+ * DataQueryService (Antigo JSK)
3
3
  * Responsável pela execução e processamento de consultas assíncronas.
4
4
  */
5
5
  class DataQueryService {
@@ -53,12 +53,15 @@ class DataQueryService {
53
53
  * @returns {Promise<Array<Object>>} Promise resolvendo com os dados.
54
54
  */
55
55
  static async fetch(query, params = null) {
56
- if (typeof this.executor !== 'function') {
57
- return Promise.reject(new Error("Executor de query não configurado. Use DataQueryService.setExecutor()."));
56
+ // Tenta usar o executor configurado ou busca o global executeQuery como fallback
57
+ const executor = this.executor || (typeof window !== 'undefined' ? window.executeQuery : null);
58
+
59
+ if (typeof executor !== 'function') {
60
+ return Promise.reject(new Error("Executor de query não configurado e 'executeQuery' global não encontrado."));
58
61
  }
59
62
 
60
63
  return new Promise((resolve, reject) => {
61
- this.executor(query, params,
64
+ executor(query, params,
62
65
  (rawValue) => {
63
66
  try {
64
67
  const data = DataQueryService.normalizeResponse(rawValue);
@@ -107,14 +110,12 @@ class DataQueryService {
107
110
  }
108
111
 
109
112
  /**
110
- * FormatUtils
113
+ * FormatUtils (Antigo JFSK)
111
114
  * Utilitários para formatação de moeda, números e datas (Locale pt-BR).
112
115
  */
113
116
  class FormatUtils {
114
117
  /**
115
118
  * Formata valor para moeda BRL (R$).
116
- * @param {number|string} value
117
- * @returns {string} Ex: "R$ 1.250,00"
118
119
  */
119
120
  static currency(value) {
120
121
  const numberVal = parseFloat(value);
@@ -128,8 +129,6 @@ class FormatUtils {
128
129
 
129
130
  /**
130
131
  * Formata número inteiro com separadores de milhar.
131
- * @param {number|string} value
132
- * @returns {string} Ex: "1.000"
133
132
  */
134
133
  static number(value) {
135
134
  const numberVal = parseFloat(value);
@@ -142,8 +141,6 @@ class FormatUtils {
142
141
 
143
142
  /**
144
143
  * Formata número decimal com 2 casas fixas.
145
- * @param {number|string} value
146
- * @returns {string} Ex: "1.200,50"
147
144
  */
148
145
  static decimal(value) {
149
146
  const numberVal = parseFloat(value);
@@ -157,7 +154,6 @@ class FormatUtils {
157
154
 
158
155
  /**
159
156
  * Retorna data atual no formato DD/MM/YYYY.
160
- * @returns {string}
161
157
  */
162
158
  static currentDate() {
163
159
  return new Intl.DateTimeFormat('pt-BR').format(new Date());
@@ -165,22 +161,16 @@ class FormatUtils {
165
161
 
166
162
  /**
167
163
  * Converte string ISO (YYYY-MM-DD) para PT-BR (DD/MM/YYYY).
168
- * @param {string} isoDateString
169
- * @returns {string}
170
164
  */
171
165
  static formatDateToBR(isoDateString) {
172
166
  if (!isoDateString) return '';
173
167
  const parts = isoDateString.split('-');
174
168
  if (parts.length !== 3) return isoDateString;
175
-
176
- // [Ano, Mes, Dia] -> "Dia/Mes/Ano"
177
169
  return `${parts[2]}/${parts[1]}/${parts[0]}`;
178
170
  }
179
171
 
180
172
  /**
181
173
  * Retorna data atual em ISO (YYYY-MM-DD).
182
- * Útil para inputs HTML tipo date.
183
- * @returns {string}
184
174
  */
185
175
  static currentIsoDate() {
186
176
  return new Date().toISOString().split('T')[0];
@@ -188,7 +178,6 @@ class FormatUtils {
188
178
 
189
179
  /**
190
180
  * Data e Hora atuais (DD/MM/YYYY HH:mm).
191
- * @returns {string}
192
181
  */
193
182
  static currentDateTime() {
194
183
  const now = new Date();
@@ -199,17 +188,10 @@ class FormatUtils {
199
188
  }
200
189
 
201
190
  /**
202
- * SortUtils
191
+ * SortUtils (Antigo JOSK)
203
192
  * Utilitários para ordenação de listas.
204
193
  */
205
194
  class SortUtils {
206
- /**
207
- * Ordena array de objetos.
208
- * @param {Array<Object>} data Lista original.
209
- * @param {string} key Chave do objeto para ordenar.
210
- * @param {'asc'|'desc'} direction Direção da ordenação.
211
- * @returns {Array<Object>} Nova lista ordenada.
212
- */
213
195
  static sortBy(data, key, direction = 'asc') {
214
196
  if (!Array.isArray(data) || !key) return data;
215
197
 
@@ -234,16 +216,12 @@ class SortUtils {
234
216
  }
235
217
 
236
218
  /**
237
- * ExportService
219
+ * ExportService (Antigo JEXSK)
238
220
  * Exportação para Excel (.xlsx) e CSV.
239
221
  */
240
222
  class ExportService {
241
223
  static CDN_URL = "https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js";
242
224
 
243
- /**
244
- * Carrega biblioteca externa (SheetJS) sob demanda.
245
- * @private
246
- */
247
225
  static async loadDependency() {
248
226
  if (typeof window !== 'undefined' && window.XLSX) return;
249
227
 
@@ -257,17 +235,8 @@ class ExportService {
257
235
  });
258
236
  }
259
237
 
260
- /**
261
- * Gera arquivo Excel.
262
- * @param {Array<Object>} data Dados brutos.
263
- * @param {Array<{key: string, display: string}>} columns Definição de colunas.
264
- * @param {string} filename Nome do arquivo (sem extensão).
265
- * @param {string} sheetName Nome da aba.
266
- */
267
238
  static async toExcel(data, columns, filename, sheetName = 'Dados') {
268
239
  await this.loadDependency();
269
-
270
- // Mapeia os dados para as chaves de exibição
271
240
  const formattedData = data.map(item => {
272
241
  const row = {};
273
242
  columns.forEach(col => {
@@ -282,28 +251,18 @@ class ExportService {
282
251
  XLSX.writeFile(workbook, `${filename}.xlsx`);
283
252
  }
284
253
 
285
- /**
286
- * Gera arquivo CSV.
287
- * @param {Array<Object>} data Dados brutos.
288
- * @param {Array<{key: string, display: string}>} columns Definição de colunas.
289
- * @param {string} filename Nome do arquivo (sem extensão).
290
- */
291
254
  static toCSV(data, columns, filename) {
292
255
  const headerRow = columns.map(c => `"${c.display}"`).join(';');
293
-
294
256
  const bodyRows = data.map(item => {
295
257
  return columns.map(col => {
296
- const val = item[col.key] ?? '';
258
+ const val = item[col.key] ?? '';
297
259
  const stringVal = String(val).replace(/"/g, '""').replace(/\r?\n|\r/g, ' ');
298
260
  return `"${stringVal}"`;
299
261
  }).join(';');
300
262
  });
301
-
302
263
  const csvContent = [headerRow, ...bodyRows].join('\r\n');
303
-
304
264
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
305
265
  const link = document.createElement('a');
306
-
307
266
  if (link.download !== undefined) {
308
267
  const url = URL.createObjectURL(blob);
309
268
  link.setAttribute('href', url);
@@ -315,31 +274,35 @@ class ExportService {
315
274
  }
316
275
  }
317
276
 
318
- /**
319
- * Método principal de exportação.
320
- */
321
277
  static async export(data, columns, filename = 'export', format = 'xlsx') {
322
278
  if (!data?.length) throw new Error("Sem dados para exportar.");
323
279
  if (!columns?.length) throw new Error("Colunas não definidas.");
324
280
 
325
281
  const fmt = format.toLowerCase();
326
-
327
- if (fmt === 'xlsx') {
328
- await this.toExcel(data, columns, filename);
329
- } else if (fmt === 'csv') {
330
- this.toCSV(data, columns, filename);
331
- } else {
332
- throw new Error(`Formato '${format}' não suportado. Use 'xlsx' ou 'csv'.`);
333
- }
282
+ if (fmt === 'xlsx') await this.toExcel(data, columns, filename);
283
+ else if (fmt === 'csv') this.toCSV(data, columns, filename);
284
+ else throw new Error(`Formato '${format}' não suportado.`);
334
285
  }
335
286
  }
336
287
 
288
+ if (typeof window !== 'undefined') {
289
+ window.JSK = DataQueryService;
290
+ window.JFSK = FormatUtils;
291
+ window.JOSK = SortUtils;
292
+ window.JEXSK = ExportService;
293
+
294
+ if (typeof window.executeQuery === 'function') {
295
+ DataQueryService.setExecutor(window.executeQuery);
296
+ console.log("[DataQueryService] Executor 'executeQuery' detectado e configurado automaticamente.");
297
+ }
298
+ }
337
299
 
338
300
  export {
339
301
  DataQueryService,
340
302
  FormatUtils,
341
303
  SortUtils,
342
304
  ExportService,
305
+ // Aliases
343
306
  DataQueryService as JSK,
344
307
  FormatUtils as JFSK,
345
308
  SortUtils as JOSK,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jtandrelevicius/utils-js-library",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "scripts": {