@danielarndt0/cnpj-db-loader 2.3.0 → 2.4.0-beta.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.
package/dist/index.js CHANGED
@@ -3269,6 +3269,15 @@ function createFieldValueParser(dataType) {
3269
3269
  };
3270
3270
  }
3271
3271
  }
3272
+ function toDatabaseValue(dataType, rawValue) {
3273
+ return createFieldValueParser(dataType)(rawValue);
3274
+ }
3275
+ function normalizeCode(value, fallback) {
3276
+ if (typeof value === "string" && value.trim() !== "") {
3277
+ return value.trim();
3278
+ }
3279
+ return fallback;
3280
+ }
3272
3281
  function createPartnerDedupeKeyBuilder(indices) {
3273
3282
  const orderedIndices = [
3274
3283
  indices.cnpjRoot,
@@ -3296,6 +3305,60 @@ function createEstablishmentCnpjFullBuilder(indices) {
3296
3305
  return `${root}${order}${digits}`;
3297
3306
  };
3298
3307
  }
3308
+ function buildPartnerDedupeKey(recordByColumn) {
3309
+ return [
3310
+ recordByColumn.cnpj_root,
3311
+ recordByColumn.partner_type_code,
3312
+ recordByColumn.partner_name,
3313
+ recordByColumn.partner_document,
3314
+ recordByColumn.partner_qualification_code,
3315
+ recordByColumn.entry_date,
3316
+ recordByColumn.country_code,
3317
+ recordByColumn.legal_representative_document,
3318
+ recordByColumn.legal_representative_name,
3319
+ recordByColumn.legal_representative_qualification_code,
3320
+ recordByColumn.age_group_code
3321
+ ].map((value) => value == null ? "" : String(value).trim()).join("|");
3322
+ }
3323
+ function transformRecord(dataset, layout, rawFields, schemaCapabilities, writeTarget) {
3324
+ const values = layout.fields.map(
3325
+ (field, index) => toDatabaseValue(field.dataType, rawFields[index] ?? "")
3326
+ );
3327
+ const recordByColumn = Object.fromEntries(
3328
+ layout.fields.map((field, index) => [field.columnName, values[index]])
3329
+ );
3330
+ if (dataset === "companies") {
3331
+ recordByColumn.company_size_code = normalizeCode(
3332
+ recordByColumn.company_size_code,
3333
+ "00"
3334
+ );
3335
+ }
3336
+ if (dataset === "establishments") {
3337
+ recordByColumn.branch_type_code = normalizeCode(
3338
+ recordByColumn.branch_type_code,
3339
+ "1"
3340
+ );
3341
+ recordByColumn.registration_status_code = normalizeCode(
3342
+ recordByColumn.registration_status_code,
3343
+ "01"
3344
+ );
3345
+ }
3346
+ const normalizedValues = layout.fields.map(
3347
+ (field) => recordByColumn[field.columnName]
3348
+ );
3349
+ if (writeTarget === "final") {
3350
+ if (dataset === "establishments" && schemaCapabilities.includeEstablishmentCnpjFullInInsert) {
3351
+ return [
3352
+ ...normalizedValues,
3353
+ `${recordByColumn.cnpj_root ?? ""}${recordByColumn.cnpj_order ?? ""}${recordByColumn.cnpj_check_digits ?? ""}`
3354
+ ];
3355
+ }
3356
+ if (dataset === "partners" && schemaCapabilities.includePartnerDedupeKeyInInsert) {
3357
+ return [...normalizedValues, buildPartnerDedupeKey(recordByColumn)];
3358
+ }
3359
+ }
3360
+ return normalizedValues;
3361
+ }
3299
3362
  function buildParsedPayload(columns, values) {
3300
3363
  return Object.fromEntries(
3301
3364
  columns.map((column, index) => [column, values[index] ?? null])
@@ -3435,7 +3498,7 @@ function createImportRowNormalizer(input) {
3435
3498
  "cnpj_check_digits"
3436
3499
  )
3437
3500
  }) : null;
3438
- const buildPartnerDedupeKey = appendPartnerDedupeKey ? createPartnerDedupeKeyBuilder({
3501
+ const buildPartnerDedupeKey2 = appendPartnerDedupeKey ? createPartnerDedupeKeyBuilder({
3439
3502
  cnpjRoot: resolveLayoutColumnIndex(input.layout, "cnpj_root"),
3440
3503
  partnerTypeCode: resolveLayoutColumnIndex(
3441
3504
  input.layout,
@@ -3495,8 +3558,8 @@ function createImportRowNormalizer(input) {
3495
3558
  if (buildEstablishmentCnpjFull) {
3496
3559
  values.push(buildEstablishmentCnpjFull(values));
3497
3560
  }
3498
- if (buildPartnerDedupeKey) {
3499
- values.push(buildPartnerDedupeKey(values));
3561
+ if (buildPartnerDedupeKey2) {
3562
+ values.push(buildPartnerDedupeKey2(values));
3500
3563
  }
3501
3564
  return {
3502
3565
  values,
@@ -8096,6 +8159,851 @@ async function syncFederalRevenueDataset(options = {}) {
8096
8159
  () => runFederalRevenueSyncPipeline(options, check.selectedReference)
8097
8160
  );
8098
8161
  }
8162
+
8163
+ // src/services/postgres-direct/exporter.ts
8164
+ import { createWriteStream as createWriteStream3 } from "fs";
8165
+ import { mkdir as mkdir8, writeFile as writeFile5 } from "fs/promises";
8166
+ import path16 from "path";
8167
+
8168
+ // src/services/postgres-direct/csv.ts
8169
+ function formatCsvValue(value) {
8170
+ if (value === null || value === void 0) {
8171
+ return "";
8172
+ }
8173
+ if (value instanceof Date) {
8174
+ return formatCsvValue(value.toISOString());
8175
+ }
8176
+ const text = String(value);
8177
+ const shouldQuote = /[",\r\n]/.test(text);
8178
+ if (!shouldQuote) {
8179
+ return text;
8180
+ }
8181
+ return `"${text.replace(/"/g, '""')}"`;
8182
+ }
8183
+ function formatCsvRow(values) {
8184
+ return values.map(formatCsvValue).join(",");
8185
+ }
8186
+
8187
+ // src/services/postgres-direct/script.ts
8188
+ import path15 from "path";
8189
+ var STAGING_DATASETS = [
8190
+ "companies",
8191
+ "establishments",
8192
+ "partners",
8193
+ "simples_options"
8194
+ ];
8195
+ var DOMAIN_DATASETS = [
8196
+ "partner_qualifications",
8197
+ "legal_natures",
8198
+ "countries",
8199
+ "cities",
8200
+ "reasons",
8201
+ "cnaes"
8202
+ ];
8203
+ var STAGING_TABLE_BY_DATASET3 = {
8204
+ companies: "staging_companies",
8205
+ establishments: "staging_establishments",
8206
+ partners: "staging_partners",
8207
+ simples_options: "staging_simples_options"
8208
+ };
8209
+ function quoteSqlLiteral(value) {
8210
+ return `'${value.replace(/'/g, "''")}'`;
8211
+ }
8212
+ function quoteIdentifier(value) {
8213
+ return `"${value.replace(/"/g, '""')}"`;
8214
+ }
8215
+ function normalizePathForPsql(filePath) {
8216
+ return path15.resolve(filePath).replace(/\\/g, "/");
8217
+ }
8218
+ function csvCopyCommand(tableName, columns, filePath) {
8219
+ const normalizedFilePath = normalizePathForPsql(filePath);
8220
+ return `\\copy ${tableName} (${columns.join(", ")}) from ${quoteSqlLiteral(normalizedFilePath)} with (format csv, header true, delimiter ',', quote '"', escape '"', null '')`;
8221
+ }
8222
+ function receitaCopyCommand(tableName, columns, filePath) {
8223
+ const normalizedFilePath = normalizePathForPsql(filePath);
8224
+ return `\\copy ${tableName} (${columns.join(", ")}) from ${quoteSqlLiteral(normalizedFilePath)} with (format csv, header false, delimiter ';', quote '"', escape '"')`;
8225
+ }
8226
+ function datasetColumns(dataset) {
8227
+ return DATASET_LAYOUTS[dataset].fields.map((field) => field.columnName);
8228
+ }
8229
+ function updateAssignments(columns, excludedColumns) {
8230
+ return columns.filter((column) => !excludedColumns.includes(column)).map((column) => `${column} = excluded.${column}`).concat(["updated_at = now()"]).join(",\n ");
8231
+ }
8232
+ function partnerDedupeExpression(alias) {
8233
+ return [
8234
+ "md5(",
8235
+ ` coalesce(${alias}.cnpj_root, '') || '|' ||`,
8236
+ ` coalesce(${alias}.partner_type_code, '') || '|' ||`,
8237
+ ` coalesce(${alias}.partner_name, '') || '|' ||`,
8238
+ ` coalesce(${alias}.partner_document, '') || '|' ||`,
8239
+ ` coalesce(${alias}.partner_qualification_code, '') || '|' ||`,
8240
+ ` coalesce((${alias}.entry_date - date '2000-01-01')::text, '') || '|' ||`,
8241
+ ` coalesce(${alias}.country_code, '') || '|' ||`,
8242
+ ` coalesce(${alias}.legal_representative_document, '') || '|' ||`,
8243
+ ` coalesce(${alias}.legal_representative_name, '') || '|' ||`,
8244
+ ` coalesce(${alias}.legal_representative_qualification_code, '') || '|' ||`,
8245
+ ` coalesce(${alias}.age_group_code, '')`,
8246
+ ")"
8247
+ ].join("\n");
8248
+ }
8249
+ function materializeCompaniesSql() {
8250
+ const columns = companiesLayout.fields.map((field) => field.columnName);
8251
+ return [
8252
+ "\\echo 'Materializing companies...'",
8253
+ "with source as (",
8254
+ " select",
8255
+ ` ${columns.map((column) => `source.${column}`).join(",\n ")},`,
8256
+ " row_number() over (partition by source.cnpj_root order by source.staging_id desc) as dedupe_rank",
8257
+ " from staging_companies source",
8258
+ "),",
8259
+ "deduped as (",
8260
+ " select * from source where dedupe_rank = 1",
8261
+ ")",
8262
+ `insert into companies (${columns.join(", ")})`,
8263
+ `select ${columns.join(", ")}`,
8264
+ "from deduped",
8265
+ "on conflict (cnpj_root) do update set",
8266
+ ` ${updateAssignments(columns, ["cnpj_root"])};`
8267
+ ].join("\n");
8268
+ }
8269
+ function materializeEstablishmentsSql() {
8270
+ const baseColumns = establishmentsLayout.fields.map(
8271
+ (field) => field.columnName
8272
+ );
8273
+ const insertColumns = [...baseColumns, "cnpj_full"];
8274
+ return [
8275
+ "\\echo 'Materializing establishments and secondary CNAEs...'",
8276
+ "with source as (",
8277
+ " select",
8278
+ ` ${baseColumns.map((column) => `source.${column}`).join(",\n ")},`,
8279
+ " source.cnpj_root || source.cnpj_order || source.cnpj_check_digits as cnpj_full,",
8280
+ " row_number() over (partition by source.cnpj_root || source.cnpj_order || source.cnpj_check_digits order by source.staging_id desc) as dedupe_rank",
8281
+ " from staging_establishments source",
8282
+ "),",
8283
+ "deduped as (",
8284
+ " select * from source where dedupe_rank = 1",
8285
+ "),",
8286
+ "upserted as (",
8287
+ ` insert into establishments (${insertColumns.join(", ")})`,
8288
+ ` select ${insertColumns.join(", ")}`,
8289
+ " from deduped",
8290
+ " on conflict (cnpj_full) do update set",
8291
+ ` ${updateAssignments(insertColumns, ["cnpj_root", "cnpj_order", "cnpj_check_digits", "cnpj_full"])}`,
8292
+ " returning cnpj_full",
8293
+ "),",
8294
+ "deleted_secondary_cnaes as (",
8295
+ " delete from establishment_secondary_cnaes target",
8296
+ " using (select cnpj_full from deduped) source_keys",
8297
+ " where target.cnpj_full = source_keys.cnpj_full",
8298
+ " returning 1",
8299
+ "),",
8300
+ "secondary_cnaes_source as (",
8301
+ " select distinct",
8302
+ " deduped.cnpj_full,",
8303
+ " btrim(cnae_code) as cnae_code",
8304
+ " from deduped",
8305
+ " cross join lateral unnest(string_to_array(deduped.secondary_cnaes_raw, ',')) as cnae_code",
8306
+ " where deduped.secondary_cnaes_raw is not null",
8307
+ " and deduped.secondary_cnaes_raw <> ''",
8308
+ " and btrim(cnae_code) <> ''",
8309
+ ")",
8310
+ "insert into establishment_secondary_cnaes (cnpj_full, cnae_code)",
8311
+ "select cnpj_full, cnae_code",
8312
+ "from secondary_cnaes_source",
8313
+ "on conflict (cnpj_full, cnae_code) do nothing;"
8314
+ ].join("\n");
8315
+ }
8316
+ function materializePartnersSql() {
8317
+ const baseColumns = partnersLayout.fields.map((field) => field.columnName);
8318
+ const insertColumns = [...baseColumns, "partner_dedupe_key"];
8319
+ return [
8320
+ "\\echo 'Materializing partners...'",
8321
+ "with source as (",
8322
+ " select",
8323
+ ` ${baseColumns.map((column) => `source.${column}`).join(",\n ")},`,
8324
+ ` ${partnerDedupeExpression("source")} as partner_dedupe_key`,
8325
+ " from staging_partners source",
8326
+ "),",
8327
+ "ranked as (",
8328
+ " select",
8329
+ " source.*,",
8330
+ " row_number() over (partition by source.partner_dedupe_key order by source.cnpj_root asc) as dedupe_rank",
8331
+ " from source",
8332
+ "),",
8333
+ "deduped as (",
8334
+ " select * from ranked where dedupe_rank = 1",
8335
+ ")",
8336
+ `insert into partners (${insertColumns.join(", ")})`,
8337
+ `select ${insertColumns.join(", ")}`,
8338
+ "from deduped",
8339
+ "on conflict (partner_dedupe_key) do update set",
8340
+ ` ${updateAssignments(insertColumns, ["partner_dedupe_key"])};`
8341
+ ].join("\n");
8342
+ }
8343
+ function materializeSimplesSql() {
8344
+ const columns = simplesLayout.fields.map((field) => field.columnName);
8345
+ return [
8346
+ "\\echo 'Materializing simples options...'",
8347
+ "with source as (",
8348
+ " select",
8349
+ ` ${columns.map((column) => `source.${column}`).join(",\n ")},`,
8350
+ " row_number() over (partition by source.cnpj_root order by source.staging_id desc) as dedupe_rank",
8351
+ " from staging_simples_options source",
8352
+ "),",
8353
+ "deduped as (",
8354
+ " select * from source where dedupe_rank = 1",
8355
+ ")",
8356
+ `insert into simples_options (${columns.join(", ")})`,
8357
+ `select ${columns.join(", ")}`,
8358
+ "from deduped",
8359
+ "on conflict (cnpj_root) do update set",
8360
+ ` ${updateAssignments(columns, ["cnpj_root"])};`
8361
+ ].join("\n");
8362
+ }
8363
+ function copyDomainSql(dataset, files) {
8364
+ if (files.length === 0) {
8365
+ return [];
8366
+ }
8367
+ const columns = datasetColumns(dataset);
8368
+ const tempTable = `tmp_hybrid_${dataset}`;
8369
+ const lines = [
8370
+ `\\echo 'Loading ${dataset} lookup data...'`,
8371
+ `drop table if exists ${tempTable};`,
8372
+ `create temporary table ${tempTable} (code text, description text);`
8373
+ ];
8374
+ for (const file of files) {
8375
+ lines.push(csvCopyCommand(tempTable, columns, file.absolutePath));
8376
+ }
8377
+ lines.push(
8378
+ `insert into ${dataset} (${columns.join(", ")})`,
8379
+ `select distinct on (code) ${columns.join(", ")}`,
8380
+ `from ${tempTable}`,
8381
+ "where code is not null and code <> ''",
8382
+ "order by code",
8383
+ "on conflict (code) do update set description = excluded.description;"
8384
+ );
8385
+ return lines;
8386
+ }
8387
+ function copyStagingSql(dataset, files) {
8388
+ if (files.length === 0) {
8389
+ return [];
8390
+ }
8391
+ const tableName = STAGING_TABLE_BY_DATASET3[dataset];
8392
+ if (!tableName) {
8393
+ return [];
8394
+ }
8395
+ const columns = datasetColumns(dataset);
8396
+ return [
8397
+ `\\echo 'Loading ${dataset} staging data...'`,
8398
+ ...files.map(
8399
+ (file) => csvCopyCommand(tableName, columns, file.absolutePath)
8400
+ )
8401
+ ];
8402
+ }
8403
+ function csvFilesByDataset(files) {
8404
+ const grouped = {};
8405
+ for (const file of files) {
8406
+ const items = grouped[file.dataset] ?? [];
8407
+ items.push(file);
8408
+ grouped[file.dataset] = items;
8409
+ }
8410
+ return grouped;
8411
+ }
8412
+ function directFilesByDataset(files) {
8413
+ const grouped = {};
8414
+ for (const file of files) {
8415
+ const items = grouped[file.dataset] ?? [];
8416
+ items.push(file);
8417
+ grouped[file.dataset] = items;
8418
+ }
8419
+ return grouped;
8420
+ }
8421
+ function rawTableName(dataset) {
8422
+ return `tmp_hybrid_raw_${dataset}`;
8423
+ }
8424
+ function createRawTempTableSql(dataset) {
8425
+ const columns = DATASET_LAYOUTS[dataset].fields.map((field) => ` ${quoteIdentifier(field.columnName)} text`).join(",\n");
8426
+ return [
8427
+ `drop table if exists ${rawTableName(dataset)};`,
8428
+ `create temporary table ${rawTableName(dataset)} (`,
8429
+ columns,
8430
+ ");"
8431
+ ].join("\n");
8432
+ }
8433
+ function textExpression(alias, column) {
8434
+ return `nullif(btrim(${alias}.${quoteIdentifier(column)}), '')`;
8435
+ }
8436
+ function dateExpression(alias, column) {
8437
+ const value = `btrim(${alias}.${quoteIdentifier(column)})`;
8438
+ return [
8439
+ "case",
8440
+ ` when ${value} = '' or ${value} = '00000000' then null`,
8441
+ ` when ${value} ~ '^\\d{8}$' then to_date(${value}, 'YYYYMMDD')`,
8442
+ " else null",
8443
+ "end"
8444
+ ].join(" ");
8445
+ }
8446
+ function numericExpression(alias, column) {
8447
+ const value = `btrim(${alias}.${quoteIdentifier(column)})`;
8448
+ return [
8449
+ "case",
8450
+ ` when ${value} = '' then null`,
8451
+ ` when ${value} like '%,%' and ${value} like '%.%' then replace(replace(${value}, '.', ''), ',', '.')::numeric`,
8452
+ ` when ${value} like '%,%' then replace(${value}, ',', '.')::numeric`,
8453
+ ` else ${value}::numeric`,
8454
+ "end"
8455
+ ].join(" ");
8456
+ }
8457
+ function integerExpression(alias, column) {
8458
+ const value = `btrim(${alias}.${quoteIdentifier(column)})`;
8459
+ return [
8460
+ "case",
8461
+ ` when ${value} = '' then null`,
8462
+ ` when ${value} ~ '^-?\\d+$' then ${value}::integer`,
8463
+ " else null",
8464
+ "end"
8465
+ ].join(" ");
8466
+ }
8467
+ function booleanExpression(alias, column) {
8468
+ const value = `lower(btrim(${alias}.${quoteIdentifier(column)}))`;
8469
+ return [
8470
+ "case",
8471
+ ` when ${value} in ('1', 'true', 't', 'y', 'yes', 's') then true`,
8472
+ ` when ${value} in ('0', 'false', 'f', 'n', 'no') then false`,
8473
+ " else null",
8474
+ "end"
8475
+ ].join(" ");
8476
+ }
8477
+ function fieldExpression(dataset, field, alias) {
8478
+ const column = field.columnName;
8479
+ if (dataset === "companies" && column === "company_size_code") {
8480
+ return `coalesce(${textExpression(alias, column)}, '00')`;
8481
+ }
8482
+ if (dataset === "establishments" && column === "branch_type_code") {
8483
+ return `coalesce(${textExpression(alias, column)}, '1')`;
8484
+ }
8485
+ if (dataset === "establishments" && column === "registration_status_code") {
8486
+ return `coalesce(${textExpression(alias, column)}, '01')`;
8487
+ }
8488
+ switch (field.dataType) {
8489
+ case "date":
8490
+ return dateExpression(alias, column);
8491
+ case "numeric":
8492
+ return numericExpression(alias, column);
8493
+ case "integer":
8494
+ return integerExpression(alias, column);
8495
+ case "boolean":
8496
+ return booleanExpression(alias, column);
8497
+ default:
8498
+ return textExpression(alias, column);
8499
+ }
8500
+ }
8501
+ function rawDomainSql(dataset, files) {
8502
+ if (files.length === 0) {
8503
+ return [];
8504
+ }
8505
+ const layout = DATASET_LAYOUTS[dataset];
8506
+ const columns = layout.fields.map((field) => field.columnName);
8507
+ const tableName = rawTableName(dataset);
8508
+ const lines = [
8509
+ `\\echo 'Loading ${dataset} lookup data directly from sanitized Receita files...'`,
8510
+ createRawTempTableSql(dataset)
8511
+ ];
8512
+ for (const file of files) {
8513
+ lines.push(receitaCopyCommand(tableName, columns, file.absolutePath));
8514
+ }
8515
+ lines.push(
8516
+ `insert into ${dataset} (${columns.join(", ")})`,
8517
+ "select distinct on (code)",
8518
+ " nullif(btrim(code), '') as code,",
8519
+ " nullif(btrim(description), '') as description",
8520
+ `from ${tableName}`,
8521
+ "where nullif(btrim(code), '') is not null",
8522
+ "order by code",
8523
+ "on conflict (code) do update set description = excluded.description;"
8524
+ );
8525
+ return lines;
8526
+ }
8527
+ function rawStagingSql(dataset, files) {
8528
+ if (files.length === 0) {
8529
+ return [];
8530
+ }
8531
+ const targetTable = STAGING_TABLE_BY_DATASET3[dataset];
8532
+ if (!targetTable) {
8533
+ return [];
8534
+ }
8535
+ const layout = DATASET_LAYOUTS[dataset];
8536
+ const columns = layout.fields.map((field) => field.columnName);
8537
+ const tableName = rawTableName(dataset);
8538
+ const alias = "source";
8539
+ const expressions = layout.fields.map(
8540
+ (field) => ` ${fieldExpression(dataset, field, alias)} as ${field.columnName}`
8541
+ );
8542
+ const lines = [
8543
+ `\\echo 'Loading ${dataset} staging data directly from sanitized Receita files...'`,
8544
+ createRawTempTableSql(dataset)
8545
+ ];
8546
+ for (const file of files) {
8547
+ lines.push(receitaCopyCommand(tableName, columns, file.absolutePath));
8548
+ }
8549
+ lines.push(
8550
+ `insert into ${targetTable} (${columns.join(", ")})`,
8551
+ "select",
8552
+ expressions.join(",\n"),
8553
+ `from ${tableName} ${alias};`
8554
+ );
8555
+ return lines;
8556
+ }
8557
+ function generatePostgresDirectImportScript(input) {
8558
+ const grouped = csvFilesByDataset(input.files);
8559
+ const lines = [
8560
+ "-- CNPJ DB Loader hybrid PostgreSQL import script",
8561
+ "-- Generated from PostgreSQL-ready CSV files exported by cnpj-db-loader postgres export-csv.",
8562
+ "-- Execute with psql, for example:",
8563
+ '-- psql "postgres://postgres:postgres@localhost:5432/cnpj" -f import-postgres-direct.sql',
8564
+ "",
8565
+ "\\set ON_ERROR_STOP on",
8566
+ "\\echo 'Starting CNPJ DB Loader hybrid PostgreSQL import...'",
8567
+ "",
8568
+ "begin;",
8569
+ "",
8570
+ "-- Keep the final schema and seed data managed by sql/schema.sql.",
8571
+ "-- This script only resets staging tables and then upserts final data.",
8572
+ "truncate table staging_companies restart identity;",
8573
+ "truncate table staging_establishments restart identity;",
8574
+ "truncate table staging_partners restart identity;",
8575
+ "truncate table staging_simples_options restart identity;",
8576
+ ""
8577
+ ];
8578
+ for (const dataset of DOMAIN_DATASETS) {
8579
+ lines.push(...copyDomainSql(dataset, grouped[dataset] ?? []), "");
8580
+ }
8581
+ for (const dataset of STAGING_DATASETS) {
8582
+ lines.push(...copyStagingSql(dataset, grouped[dataset] ?? []), "");
8583
+ }
8584
+ lines.push(...materializationAndAnalyzeSql());
8585
+ return lines.join("\n");
8586
+ }
8587
+ function generatePostgresSanitizedDirectImportScript(input) {
8588
+ const grouped = directFilesByDataset(input.files);
8589
+ const lines = [
8590
+ "-- CNPJ DB Loader direct PostgreSQL import script",
8591
+ "-- Generated from sanitized Receita files by cnpj-db-loader postgres generate-script.",
8592
+ "-- This path avoids rewriting the dataset into a second CSV tree.",
8593
+ "-- Execute with psql, for example:",
8594
+ '-- psql "postgres://postgres:postgres@localhost:5432/cnpj" -f import-postgres-direct.sql',
8595
+ "",
8596
+ "\\set ON_ERROR_STOP on",
8597
+ `\\echo 'Using source file encoding ${input.sourceEncoding} for psql copy operations...'`,
8598
+ `set client_encoding to ${quoteSqlLiteral(input.sourceEncoding)};`,
8599
+ "\\echo 'Starting CNPJ DB Loader direct PostgreSQL import from sanitized files...'",
8600
+ "",
8601
+ "begin;",
8602
+ "",
8603
+ "-- Keep the final schema and seed data managed by sql/schema.sql.",
8604
+ "-- This script copies sanitized Receita files into temporary raw tables,",
8605
+ "-- transforms values inside PostgreSQL, resets staging tables and upserts final data.",
8606
+ "truncate table staging_companies restart identity;",
8607
+ "truncate table staging_establishments restart identity;",
8608
+ "truncate table staging_partners restart identity;",
8609
+ "truncate table staging_simples_options restart identity;",
8610
+ ""
8611
+ ];
8612
+ for (const dataset of DOMAIN_DATASETS) {
8613
+ lines.push(...rawDomainSql(dataset, grouped[dataset] ?? []), "");
8614
+ }
8615
+ for (const dataset of STAGING_DATASETS) {
8616
+ lines.push(...rawStagingSql(dataset, grouped[dataset] ?? []), "");
8617
+ }
8618
+ lines.push(...materializationAndAnalyzeSql());
8619
+ return lines.join("\n");
8620
+ }
8621
+ function materializationAndAnalyzeSql() {
8622
+ return [
8623
+ materializeCompaniesSql(),
8624
+ "",
8625
+ materializeEstablishmentsSql(),
8626
+ "",
8627
+ materializePartnersSql(),
8628
+ "",
8629
+ materializeSimplesSql(),
8630
+ "",
8631
+ "\\echo 'Refreshing planner statistics...'",
8632
+ "analyze companies;",
8633
+ "analyze establishments;",
8634
+ "analyze establishment_secondary_cnaes;",
8635
+ "analyze partners;",
8636
+ "analyze simples_options;",
8637
+ "analyze cnaes;",
8638
+ "analyze cities;",
8639
+ "analyze countries;",
8640
+ "analyze legal_natures;",
8641
+ "analyze partner_qualifications;",
8642
+ "analyze reasons;",
8643
+ "",
8644
+ "commit;",
8645
+ "",
8646
+ "\\echo 'CNPJ DB Loader hybrid PostgreSQL import completed.'",
8647
+ ""
8648
+ ];
8649
+ }
8650
+
8651
+ // src/services/postgres-direct/exporter.ts
8652
+ var POSTGRES_DIRECT_SCHEMA_CAPABILITIES = {
8653
+ includeEstablishmentCnpjFullInInsert: true,
8654
+ includeEstablishmentSecondaryCnaesTable: true,
8655
+ includePartnerDedupeKeyInInsert: true,
8656
+ requiresLookupReconciliation: false
8657
+ };
8658
+ function defaultPostgresCsvOutputPath(inputPath) {
8659
+ const baseName = path16.basename(inputPath);
8660
+ return path16.join(path16.dirname(inputPath), `${baseName}-postgres-csv`);
8661
+ }
8662
+ function normalizeOutputFileName(relativePath) {
8663
+ const parsed = path16.parse(relativePath);
8664
+ const baseName = parsed.name || parsed.base || "dataset";
8665
+ return path16.join(parsed.dir, `${baseName}.csv`);
8666
+ }
8667
+ function resolveDatasetOutputPath(outputPath, dataset, relativePath) {
8668
+ return path16.join(outputPath, dataset, normalizeOutputFileName(relativePath));
8669
+ }
8670
+ function inferNextStep4(scriptPath) {
8671
+ return `psql "postgres://postgres:postgres@localhost:5432/cnpj" -f ${scriptPath.replace(/\\/g, "/")}`;
8672
+ }
8673
+ async function writeCsvFile(input) {
8674
+ const layout = DATASET_LAYOUTS[input.dataset];
8675
+ const columns = layout.fields.map((field) => field.columnName);
8676
+ await mkdir8(path16.dirname(input.outputFile), { recursive: true });
8677
+ const output = createWriteStream3(input.outputFile, { encoding: "utf8" });
8678
+ let rows = 0;
8679
+ try {
8680
+ output.write(`${formatCsvRow(columns)}
8681
+ `);
8682
+ for await (const sourceLine of readImportSourceLines(input.inputFile)) {
8683
+ if (sourceLine.rawLine.trim() === "") {
8684
+ continue;
8685
+ }
8686
+ const parsed = parseImportSourceLine(sourceLine);
8687
+ const normalizedFields = normalizeFieldCount(
8688
+ parsed.fields,
8689
+ layout.fields.length,
8690
+ input.inputFile,
8691
+ parsed.lineNumber
8692
+ );
8693
+ const values = transformRecord(
8694
+ input.dataset,
8695
+ layout,
8696
+ normalizedFields,
8697
+ POSTGRES_DIRECT_SCHEMA_CAPABILITIES,
8698
+ "staging"
8699
+ );
8700
+ output.write(`${formatCsvRow(values)}
8701
+ `);
8702
+ rows += 1;
8703
+ }
8704
+ } finally {
8705
+ output.end();
8706
+ await new Promise((resolve, reject) => {
8707
+ output.on("finish", () => resolve());
8708
+ output.on("error", (error) => reject(error));
8709
+ });
8710
+ }
8711
+ return rows;
8712
+ }
8713
+ async function exportPostgresCsvDataset(inputPath, options = {}) {
8714
+ if (options.dataset && !isImportDatasetType(options.dataset)) {
8715
+ throw new ValidationError(`Unsupported dataset type: ${options.dataset}.`);
8716
+ }
8717
+ const validation = await validateInputDirectory(inputPath);
8718
+ if (!validation.ok) {
8719
+ throw new ValidationError(
8720
+ `The input directory is not ready for PostgreSQL CSV export. ${validation.errors.join(" ")}`
8721
+ );
8722
+ }
8723
+ const validatedPath = validation.validatedPath;
8724
+ const outputPath = path16.resolve(
8725
+ options.outputPath ?? defaultPostgresCsvOutputPath(validatedPath)
8726
+ );
8727
+ const inspected = await inspectFiles(validatedPath);
8728
+ const recognizedFiles = inspected.entries.filter((entry) => entry.entryKind === "file").flatMap((entry) => {
8729
+ if (!isImportDatasetType(entry.inferredType)) {
8730
+ return [];
8731
+ }
8732
+ if (options.dataset && entry.inferredType !== options.dataset) {
8733
+ return [];
8734
+ }
8735
+ return [{ ...entry, inferredType: entry.inferredType }];
8736
+ }).sort(sortEntries);
8737
+ if (recognizedFiles.length === 0) {
8738
+ throw new ValidationError(
8739
+ "No recognized dataset files were found for PostgreSQL CSV export."
8740
+ );
8741
+ }
8742
+ const datasets = [
8743
+ ...new Set(recognizedFiles.map((entry) => entry.inferredType))
8744
+ ].sort(
8745
+ (left, right) => IMPORT_ORDER.indexOf(left) - IMPORT_ORDER.indexOf(right)
8746
+ );
8747
+ options.onProgress?.({
8748
+ kind: "start",
8749
+ inputPath: path16.resolve(inputPath),
8750
+ validatedPath,
8751
+ outputPath,
8752
+ totalFiles: recognizedFiles.length,
8753
+ datasets
8754
+ });
8755
+ const exportedFiles = [];
8756
+ const summariesByDataset = /* @__PURE__ */ new Map();
8757
+ for (const [index, entry] of recognizedFiles.entries()) {
8758
+ const dataset = entry.inferredType;
8759
+ const inputFile = path16.join(validatedPath, entry.relativePath);
8760
+ const outputFile = resolveDatasetOutputPath(
8761
+ outputPath,
8762
+ dataset,
8763
+ entry.relativePath
8764
+ );
8765
+ options.onProgress?.({
8766
+ kind: "file_start",
8767
+ dataset,
8768
+ fileIndex: index + 1,
8769
+ totalFiles: recognizedFiles.length,
8770
+ inputFile: buildDisplayPath(inputFile),
8771
+ outputFile
8772
+ });
8773
+ const rowCount = await writeCsvFile({ dataset, inputFile, outputFile });
8774
+ exportedFiles.push({
8775
+ dataset,
8776
+ absolutePath: outputFile,
8777
+ relativePath: path16.relative(outputPath, outputFile),
8778
+ rowCount
8779
+ });
8780
+ const currentSummary = summariesByDataset.get(dataset) ?? {
8781
+ dataset,
8782
+ files: 0,
8783
+ rows: 0,
8784
+ outputFiles: []
8785
+ };
8786
+ currentSummary.files += 1;
8787
+ currentSummary.rows += rowCount;
8788
+ currentSummary.outputFiles.push(outputFile);
8789
+ summariesByDataset.set(dataset, currentSummary);
8790
+ options.onProgress?.({
8791
+ kind: "file_finish",
8792
+ dataset,
8793
+ fileIndex: index + 1,
8794
+ totalFiles: recognizedFiles.length,
8795
+ inputFile: buildDisplayPath(inputFile),
8796
+ outputFile,
8797
+ rows: rowCount
8798
+ });
8799
+ }
8800
+ const scriptName = options.scriptName ?? "import-postgres-direct.sql";
8801
+ const scriptPath = path16.join(outputPath, scriptName);
8802
+ const script = generatePostgresDirectImportScript({ files: exportedFiles });
8803
+ await writeFile5(scriptPath, script, "utf8");
8804
+ const manifestPath = path16.join(outputPath, "manifest.json");
8805
+ const summaryDatasets = [...summariesByDataset.values()].sort(
8806
+ (left, right) => IMPORT_ORDER.indexOf(left.dataset) - IMPORT_ORDER.indexOf(right.dataset)
8807
+ );
8808
+ const totalRows = summaryDatasets.reduce((sum, item) => sum + item.rows, 0);
8809
+ const manifest = {
8810
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
8811
+ inputPath: path16.resolve(inputPath),
8812
+ validatedPath,
8813
+ outputPath,
8814
+ scriptPath,
8815
+ totalFiles: exportedFiles.length,
8816
+ totalRows,
8817
+ datasets: summaryDatasets
8818
+ };
8819
+ await writeFile5(
8820
+ manifestPath,
8821
+ `${JSON.stringify(manifest, null, 2)}
8822
+ `,
8823
+ "utf8"
8824
+ );
8825
+ options.onProgress?.({
8826
+ kind: "finish",
8827
+ outputPath,
8828
+ scriptPath,
8829
+ totalFiles: exportedFiles.length,
8830
+ totalRows
8831
+ });
8832
+ return {
8833
+ inputPath: path16.resolve(inputPath),
8834
+ validatedPath,
8835
+ outputPath,
8836
+ scriptPath,
8837
+ manifestPath,
8838
+ totalFiles: exportedFiles.length,
8839
+ totalRows,
8840
+ datasets: summaryDatasets,
8841
+ warnings: [
8842
+ "PostgreSQL-ready CSV export is intended for hybrid bulk imports after extraction, validation and sanitization.",
8843
+ "The generated SQL script resets staging tables and then upserts final tables. Review it before running against production databases."
8844
+ ],
8845
+ nextStep: inferNextStep4(scriptPath)
8846
+ };
8847
+ }
8848
+
8849
+ // src/services/postgres-direct/generator.ts
8850
+ import { mkdir as mkdir9, stat as stat7, writeFile as writeFile6 } from "fs/promises";
8851
+ import path17 from "path";
8852
+ var DEFAULT_SOURCE_ENCODING = "WIN1252";
8853
+ function defaultPostgresDirectOutputPath(inputPath) {
8854
+ const baseName = path17.basename(inputPath);
8855
+ if (baseName.toLowerCase() === "sanitized") {
8856
+ return path17.join(path17.dirname(inputPath), "postgres-direct");
8857
+ }
8858
+ return path17.join(path17.dirname(inputPath), `${baseName}-postgres-direct`);
8859
+ }
8860
+ function inferNextStep5(scriptPath) {
8861
+ return `psql "postgres://postgres:postgres@localhost:5432/cnpj" -f ${scriptPath.replace(/\\/g, "/")}`;
8862
+ }
8863
+ function normalizeSourceEncoding(value) {
8864
+ const encoding = (value ?? DEFAULT_SOURCE_ENCODING).trim();
8865
+ if (!/^[A-Za-z0-9_-]+$/.test(encoding)) {
8866
+ throw new ValidationError(
8867
+ `Invalid source encoding: ${value}. Use a PostgreSQL client encoding name such as WIN1252 or UTF8.`
8868
+ );
8869
+ }
8870
+ return encoding.toUpperCase();
8871
+ }
8872
+ async function generatePostgresDirectScript(inputPath, options = {}) {
8873
+ if (options.dataset && !isImportDatasetType(options.dataset)) {
8874
+ throw new ValidationError(`Unsupported dataset type: ${options.dataset}.`);
8875
+ }
8876
+ const validation = await validateInputDirectory(inputPath);
8877
+ if (!validation.ok && !options.dataset) {
8878
+ throw new ValidationError(
8879
+ `The input directory is not ready for PostgreSQL direct script generation. ${validation.errors.join(" ")}`
8880
+ );
8881
+ }
8882
+ const validatedPath = validation.ok ? validation.validatedPath : path17.resolve(inputPath);
8883
+ const outputPath = path17.resolve(
8884
+ options.outputPath ?? defaultPostgresDirectOutputPath(validatedPath)
8885
+ );
8886
+ const sourceEncoding = normalizeSourceEncoding(options.sourceEncoding);
8887
+ const inspected = await inspectFiles(validatedPath);
8888
+ const recognizedFiles = inspected.entries.filter((entry) => entry.entryKind === "file").flatMap((entry) => {
8889
+ if (!isImportDatasetType(entry.inferredType)) {
8890
+ return [];
8891
+ }
8892
+ if (options.dataset && entry.inferredType !== options.dataset) {
8893
+ return [];
8894
+ }
8895
+ return [{ ...entry, inferredType: entry.inferredType }];
8896
+ }).sort(sortEntries);
8897
+ if (recognizedFiles.length === 0) {
8898
+ throw new ValidationError(
8899
+ "No recognized dataset files were found for PostgreSQL direct script generation."
8900
+ );
8901
+ }
8902
+ const datasets = [
8903
+ ...new Set(recognizedFiles.map((entry) => entry.inferredType))
8904
+ ].sort(
8905
+ (left, right) => IMPORT_ORDER.indexOf(left) - IMPORT_ORDER.indexOf(right)
8906
+ );
8907
+ options.onProgress?.({
8908
+ kind: "start",
8909
+ inputPath: path17.resolve(inputPath),
8910
+ validatedPath,
8911
+ outputPath,
8912
+ totalFiles: recognizedFiles.length,
8913
+ datasets,
8914
+ sourceEncoding
8915
+ });
8916
+ await mkdir9(outputPath, { recursive: true });
8917
+ const sourceFiles = [];
8918
+ const summariesByDataset = /* @__PURE__ */ new Map();
8919
+ for (const [index, entry] of recognizedFiles.entries()) {
8920
+ const dataset = entry.inferredType;
8921
+ const absolutePath = path17.join(validatedPath, entry.relativePath);
8922
+ const fileStats = await stat7(absolutePath);
8923
+ sourceFiles.push({
8924
+ dataset,
8925
+ absolutePath,
8926
+ relativePath: entry.relativePath,
8927
+ fileSize: fileStats.size
8928
+ });
8929
+ const currentSummary = summariesByDataset.get(dataset) ?? {
8930
+ dataset,
8931
+ files: 0,
8932
+ totalBytes: 0,
8933
+ sourceFiles: []
8934
+ };
8935
+ currentSummary.files += 1;
8936
+ currentSummary.totalBytes += fileStats.size;
8937
+ currentSummary.sourceFiles.push(absolutePath);
8938
+ summariesByDataset.set(dataset, currentSummary);
8939
+ options.onProgress?.({
8940
+ kind: "file_registered",
8941
+ dataset,
8942
+ fileIndex: index + 1,
8943
+ totalFiles: recognizedFiles.length,
8944
+ inputFile: buildDisplayPath(absolutePath),
8945
+ fileSize: fileStats.size
8946
+ });
8947
+ }
8948
+ const scriptName = options.scriptName ?? "import-postgres-direct.sql";
8949
+ const scriptPath = path17.join(outputPath, scriptName);
8950
+ const script = generatePostgresSanitizedDirectImportScript({
8951
+ files: sourceFiles,
8952
+ sourceEncoding
8953
+ });
8954
+ await writeFile6(scriptPath, script, "utf8");
8955
+ const manifestPath = path17.join(outputPath, "manifest.json");
8956
+ const summaryDatasets = [...summariesByDataset.values()].sort(
8957
+ (left, right) => IMPORT_ORDER.indexOf(left.dataset) - IMPORT_ORDER.indexOf(right.dataset)
8958
+ );
8959
+ const totalBytes = summaryDatasets.reduce(
8960
+ (sum, item) => sum + item.totalBytes,
8961
+ 0
8962
+ );
8963
+ const manifest = {
8964
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
8965
+ mode: "direct-sanitized-script",
8966
+ inputPath: path17.resolve(inputPath),
8967
+ validatedPath,
8968
+ outputPath,
8969
+ scriptPath,
8970
+ sourceEncoding,
8971
+ totalFiles: sourceFiles.length,
8972
+ totalBytes,
8973
+ datasets: summaryDatasets
8974
+ };
8975
+ await writeFile6(
8976
+ manifestPath,
8977
+ `${JSON.stringify(manifest, null, 2)}
8978
+ `,
8979
+ "utf8"
8980
+ );
8981
+ options.onProgress?.({
8982
+ kind: "finish",
8983
+ outputPath,
8984
+ scriptPath,
8985
+ totalFiles: sourceFiles.length,
8986
+ totalBytes
8987
+ });
8988
+ return {
8989
+ inputPath: path17.resolve(inputPath),
8990
+ validatedPath,
8991
+ outputPath,
8992
+ scriptPath,
8993
+ manifestPath,
8994
+ sourceEncoding,
8995
+ totalFiles: sourceFiles.length,
8996
+ totalBytes,
8997
+ datasets: summaryDatasets,
8998
+ warnings: [
8999
+ ...validation.ok ? [] : validation.errors,
9000
+ "This script imports sanitized Receita files directly with psql \\copy. It avoids rewriting the full dataset into a second CSV tree.",
9001
+ "The generated script expects the database schema generated by cnpj-db-loader to be applied before execution.",
9002
+ "Use --source-encoding UTF8 only if your sanitized files are already UTF-8. The default WIN1252 matches the usual Receita file encoding."
9003
+ ],
9004
+ nextStep: inferNextStep5(scriptPath)
9005
+ };
9006
+ }
8099
9007
  export {
8100
9008
  AppError,
8101
9009
  DEFAULT_FEDERAL_REVENUE_DOWNLOAD_ROOT,
@@ -8125,8 +9033,10 @@ export {
8125
9033
  ensureDirectory,
8126
9034
  evaluateFederalRevenueManifestFile,
8127
9035
  evaluateFederalRevenueManifestFiles,
9036
+ exportPostgresCsvDataset,
8128
9037
  extractArchives,
8129
9038
  finalizeFederalRevenueManifest,
9039
+ generatePostgresDirectScript,
8130
9040
  generateSchemaSql,
8131
9041
  getAllLayouts,
8132
9042
  getCurrentFederalRevenueReference,