diff --git a/.env.example b/.env.example index 300ff71..1076410 100644 --- a/.env.example +++ b/.env.example @@ -31,9 +31,6 @@ JWT_SECRET=please_change_this_to_a_long_random_secret_in_production JWT_EXPIRES_IN=7d # 系统设置中 OSS/天河链等 Secret 的加密密钥;已安装系统请保持不变 SETTING_ENCRYPTION_KEY=please_change_this_to_a_long_random_settings_key -# 溯源码盐(决定 12 位码生成,优先于数据库缓存);已安装系统请保持不变 -TRACE_CODE_SALT=please_change_this_to_a_long_random_salt - # ===== 种子超级管理员(仅本地开发 seed.ts 使用;生产由安装向导设置)===== SEED_ADMIN_USERNAME=admin SEED_ADMIN_PASSWORD=Admin@12345 diff --git a/apps/api/package.json b/apps/api/package.json index 26200f3..80aabc8 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -35,6 +35,7 @@ "@nestjs/throttler": "^6.5.0", "@prisma/client": "^5.22.0", "adm-zip": "^0.5.18", + "archiver": "5.3.2", "bcryptjs": "^2.4.3", "bullmq": "^5.34.6", "class-transformer": "^0.5.1", diff --git a/apps/api/prisma/migrations/20260713180000_outbound_import_reliability/migration.sql b/apps/api/prisma/migrations/20260713180000_outbound_import_reliability/migration.sql deleted file mode 100644 index c1a1d43..0000000 --- a/apps/api/prisma/migrations/20260713180000_outbound_import_reliability/migration.sql +++ /dev/null @@ -1,66 +0,0 @@ --- AlterTable -ALTER TABLE `outbound_import_session` - ADD COLUMN `request_id` VARCHAR(191) NULL, - ADD COLUMN `preview_job_id` VARCHAR(191) NULL, - ADD COLUMN `import_job_id` VARCHAR(191) NULL, - ADD COLUMN `import_run_token` VARCHAR(191) NULL, - MODIFY `status` ENUM('PARSING', 'READY', 'IMPORTING', 'IMPORTED', 'PARTIAL', 'FAILED', 'EXPIRED') NOT NULL DEFAULT 'PARSING'; - --- Drop obsolete row-level blockchain fields. Blockchain state belongs to trace_code. -ALTER TABLE `outbound_import_row` - DROP COLUMN `tx_hash`, - DROP COLUMN `onchain_at`, - DROP COLUMN `block_height`; - --- Backfill job links for sessions created before these columns existed. -UPDATE `outbound_import_session` AS `session` -SET `preview_job_id` = ( - SELECT `job`.`id` - FROM `job` - WHERE `job`.`type` = 'IMPORT_OUTBOUND_PREVIEW' - AND JSON_UNQUOTE(JSON_EXTRACT(`job`.`payload`, '$.sessionId')) = `session`.`id` - ORDER BY `job`.`created_at` DESC - LIMIT 1 -) -WHERE `session`.`preview_job_id` IS NULL; - -UPDATE `outbound_import_session` AS `session` -SET `import_job_id` = ( - SELECT `job`.`id` - FROM `job` - WHERE `job`.`type` = 'IMPORT_OUTBOUND' - AND JSON_UNQUOTE(JSON_EXTRACT(`job`.`payload`, '$.sessionId')) = `session`.`id` - ORDER BY `job`.`created_at` DESC - LIMIT 1 -) -WHERE `session`.`import_job_id` IS NULL - AND `session`.`status` IN ('IMPORTING', 'IMPORTED', 'PARTIAL', 'FAILED'); - --- Normalize terminal counts produced by legacy workers that left session totals stale. -UPDATE `outbound_import_session` AS `session` -JOIN `job` AS `job` ON `job`.`id` = `session`.`import_job_id` -JOIN ( - SELECT - `session_id`, - SUM(`status` = 'IMPORTED') AS `success_count`, - SUM(`status` = 'FAILED') AS `fail_count`, - SUM(`status` = 'VALID') AS `remaining_count` - FROM `outbound_import_row` - GROUP BY `session_id` -) AS `row_count` ON `row_count`.`session_id` = `session`.`id` -SET - `session`.`valid_count` = `row_count`.`success_count`, - `session`.`invalid_count` = `row_count`.`fail_count`, - `session`.`status` = CASE - WHEN `row_count`.`success_count` > 0 AND `row_count`.`fail_count` > 0 THEN 'PARTIAL' - WHEN `row_count`.`success_count` > 0 THEN 'IMPORTED' - ELSE 'FAILED' - END -WHERE `job`.`status` IN ('SUCCESS', 'PARTIAL', 'FAILED') - AND `session`.`status` IN ('IMPORTING', 'IMPORTED', 'PARTIAL', 'FAILED') - AND `row_count`.`remaining_count` = 0; - --- CreateIndex -CREATE UNIQUE INDEX `outbound_import_session_request_id_key` ON `outbound_import_session`(`request_id`); -CREATE UNIQUE INDEX `outbound_import_session_preview_job_id_key` ON `outbound_import_session`(`preview_job_id`); -CREATE UNIQUE INDEX `outbound_import_session_import_job_id_key` ON `outbound_import_session`(`import_job_id`); diff --git a/apps/api/prisma/migrations/20260713090000_init/migration.sql b/apps/api/prisma/migrations/20260715000000_init/migration.sql similarity index 68% rename from apps/api/prisma/migrations/20260713090000_init/migration.sql rename to apps/api/prisma/migrations/20260715000000_init/migration.sql index 8e07860..2cd38c9 100644 --- a/apps/api/prisma/migrations/20260713090000_init/migration.sql +++ b/apps/api/prisma/migrations/20260715000000_init/migration.sql @@ -150,12 +150,10 @@ CREATE TABLE `batch` ( CREATE TABLE `trace_code` ( `id` BIGINT NOT NULL AUTO_INCREMENT, `short_code` VARCHAR(191) NOT NULL, + `serial_no` INTEGER NOT NULL, `artwork_id` INTEGER NOT NULL, `batch_id` INTEGER NOT NULL, `group_id` INTEGER NULL, - `out_time` DATETIME(3) NULL, - `out_images` JSON NULL, - `remark` VARCHAR(191) NULL, `status` ENUM('INACTIVE', 'ACTIVE', 'DISABLED', 'ABNORMAL') NOT NULL DEFAULT 'INACTIVE', `query_count` INTEGER NOT NULL DEFAULT 0, `first_activated_at` DATETIME(3) NULL, @@ -164,6 +162,7 @@ CREATE TABLE `trace_code` ( `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), UNIQUE INDEX `trace_code_short_code_key`(`short_code`), + UNIQUE INDEX `trace_code_serial_no_key`(`serial_no`), INDEX `trace_code_artwork_id_idx`(`artwork_id`), INDEX `trace_code_batch_id_idx`(`batch_id`), INDEX `trace_code_group_id_idx`(`group_id`), @@ -172,14 +171,17 @@ CREATE TABLE `trace_code` ( ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; -- CreateTable -CREATE TABLE `trace_code_daily_sequence` ( - `date_key` VARCHAR(6) NOT NULL, - `next_seq` INTEGER NOT NULL DEFAULT 0, +CREATE TABLE `trace_code_sequence` ( + `id` INTEGER NOT NULL, + `next_seq` INTEGER NOT NULL DEFAULT 1, `updated_at` DATETIME(3) NOT NULL, - PRIMARY KEY (`date_key`) + PRIMARY KEY (`id`) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +INSERT INTO `trace_code_sequence` (`id`, `next_seq`, `updated_at`) +VALUES (1, 1, CURRENT_TIMESTAMP(3)); + -- CreateTable CREATE TABLE `blockchain_proof` ( `id` INTEGER NOT NULL AUTO_INCREMENT, @@ -192,12 +194,19 @@ CREATE TABLE `blockchain_proof` ( `explorer_url` VARCHAR(191) NULL, `token_id` BIGINT NULL, `contract_address` VARCHAR(191) NULL, + `submitted_at` DATETIME(3) NULL, `onchain_at` DATETIME(3) NULL, - `status` ENUM('PENDING', 'CONFIRMING', 'ONCHAIN', 'FAILED') NOT NULL DEFAULT 'PENDING', + `status` ENUM('PENDING', 'SUBMITTING', 'CONFIRMING', 'ONCHAIN', 'FAILED', 'UNKNOWN') NOT NULL DEFAULT 'PENDING', + `onchain_chunk_id` VARCHAR(191) NULL, + `failure_reason` TEXT NULL, + `last_synced_at` DATETIME(3) NULL, `raw_response` JSON NULL, `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updated_at` DATETIME(3) NOT NULL, - INDEX `blockchain_proof_trace_code_id_idx`(`trace_code_id`), + INDEX `blockchain_proof_status_idx`(`status`), + INDEX `blockchain_proof_onchain_chunk_id_idx`(`onchain_chunk_id`), + UNIQUE INDEX `blockchain_proof_trace_code_id_key`(`trace_code_id`), PRIMARY KEY (`id`) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; @@ -229,7 +238,7 @@ CREATE TABLE `query_log` ( -- CreateTable CREATE TABLE `job` ( `id` VARCHAR(191) NOT NULL, - `type` ENUM('GEN_CODE', 'IMPORT_OUTBOUND', 'IMPORT_OUTBOUND_PREVIEW', 'WATERMARK', 'ONCHAIN', 'BACKUP', 'RESTORE') NOT NULL, + `type` ENUM('GEN_CODE', 'IMPORT_OUTBOUND', 'IMPORT_OUTBOUND_PREVIEW', 'BATCH_OUTBOUND', 'WATERMARK', 'ONCHAIN', 'BACKUP', 'RESTORE') NOT NULL, `status` ENUM('PENDING', 'PROCESSING', 'SUCCESS', 'PARTIAL', 'FAILED') NOT NULL DEFAULT 'PENDING', `total` INTEGER NOT NULL DEFAULT 0, `success_count` INTEGER NOT NULL DEFAULT 0, @@ -241,6 +250,100 @@ CREATE TABLE `job` ( `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), `updated_at` DATETIME(3) NOT NULL, + INDEX `job_type_idx`(`type`), + INDEX `job_status_idx`(`status`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `job_item` ( + `id` BIGINT NOT NULL AUTO_INCREMENT, + `job_id` VARCHAR(191) NOT NULL, + `trace_code_id` BIGINT NULL, + `selection_key` VARCHAR(191) NOT NULL, + `proof_id` INTEGER NULL, + `chunk_id` VARCHAR(191) NULL, + `sequence` INTEGER NOT NULL DEFAULT 0, + `short_code` VARCHAR(191) NOT NULL, + `status` ENUM('PENDING', 'PROCESSING', 'SUCCESS', 'FAILED', 'SKIPPED', 'UNKNOWN') NOT NULL DEFAULT 'PENDING', + `payload` JSON NULL, + `result` JSON NULL, + `error` TEXT NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updated_at` DATETIME(3) NOT NULL, + + INDEX `job_item_job_id_status_idx`(`job_id`, `status`), + INDEX `job_item_chunk_id_status_idx`(`chunk_id`, `status`), + INDEX `job_item_trace_code_id_idx`(`trace_code_id`), + INDEX `job_item_proof_id_idx`(`proof_id`), + UNIQUE INDEX `job_item_job_id_selection_key_key`(`job_id`, `selection_key`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `onchain_chunk` ( + `id` VARCHAR(191) NOT NULL, + `job_id` VARCHAR(191) NOT NULL, + `artwork_id` INTEGER NOT NULL, + `sequence_no` INTEGER NOT NULL, + `status` ENUM('PENDING', 'SUBMITTING', 'CONFIRMING', 'SUCCESS', 'PARTIAL', 'FAILED', 'UNKNOWN') NOT NULL DEFAULT 'PENDING', + `operate_id` VARCHAR(20) NOT NULL, + `run_token` VARCHAR(191) NULL, + `product_ids` JSON NOT NULL, + `metadata_snapshot` JSON NOT NULL, + `request_payload` JSON NOT NULL, + `response` JSON NULL, + `tx_hash` VARCHAR(191) NULL, + `contract_address` VARCHAR(191) NULL, + `base_token_id` BIGINT NULL, + `failure_reason` TEXT NULL, + `attempt_count` INTEGER NOT NULL DEFAULT 0, + `submitted_at` DATETIME(3) NULL, + `unknown_at` DATETIME(3) NULL, + `confirmed_at` DATETIME(3) NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updated_at` DATETIME(3) NOT NULL, + + UNIQUE INDEX `onchain_chunk_operate_id_key`(`operate_id`), + INDEX `onchain_chunk_status_idx`(`status`), + INDEX `onchain_chunk_status_updated_at_idx`(`status`, `updated_at`), + INDEX `onchain_chunk_artwork_id_idx`(`artwork_id`), + UNIQUE INDEX `onchain_chunk_job_id_sequence_no_key`(`job_id`, `sequence_no`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `outbound_record` ( + `id` BIGINT NOT NULL AUTO_INCREMENT, + `trace_code_id` BIGINT NOT NULL, + `out_time` DATETIME(3) NOT NULL, + `remark` TEXT NULL, + `created_by` INTEGER NULL, + `updated_by` INTEGER NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updated_at` DATETIME(3) NOT NULL, + + UNIQUE INDEX `outbound_record_trace_code_id_key`(`trace_code_id`), + INDEX `outbound_record_out_time_idx`(`out_time`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `outbound_image` ( + `id` BIGINT NOT NULL AUTO_INCREMENT, + `outbound_record_id` BIGINT NOT NULL, + `file_key` VARCHAR(512) NOT NULL, + `file_name` VARCHAR(191) NOT NULL, + `mime_type` VARCHAR(191) NOT NULL, + `size` BIGINT NOT NULL, + `width` INTEGER NOT NULL, + `height` INTEGER NOT NULL, + `sort_order` INTEGER NOT NULL DEFAULT 0, + `created_by` INTEGER NULL, + `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + + UNIQUE INDEX `outbound_image_file_key_key`(`file_key`), + INDEX `outbound_image_outbound_record_id_sort_order_idx`(`outbound_record_id`, `sort_order`), PRIMARY KEY (`id`) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; @@ -274,9 +377,13 @@ CREATE TABLE `operation_log` ( -- CreateTable CREATE TABLE `outbound_import_session` ( `id` VARCHAR(191) NOT NULL, - `status` ENUM('PARSING', 'READY', 'IMPORTING', 'IMPORTED', 'FAILED', 'EXPIRED') NOT NULL DEFAULT 'PARSING', + `status` ENUM('PARSING', 'READY', 'IMPORTING', 'IMPORTED', 'PARTIAL', 'FAILED', 'EXPIRED') NOT NULL DEFAULT 'PARSING', `file_name` VARCHAR(191) NOT NULL, `file_key` VARCHAR(512) NULL, + `request_id` VARCHAR(191) NULL, + `preview_job_id` VARCHAR(191) NULL, + `import_job_id` VARCHAR(191) NULL, + `import_run_token` VARCHAR(191) NULL, `total` INTEGER NOT NULL DEFAULT 0, `valid_count` INTEGER NOT NULL DEFAULT 0, `invalid_count` INTEGER NOT NULL DEFAULT 0, @@ -287,6 +394,9 @@ CREATE TABLE `outbound_import_session` ( `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), `updated_at` DATETIME(3) NOT NULL, + UNIQUE INDEX `outbound_import_session_request_id_key`(`request_id`), + UNIQUE INDEX `outbound_import_session_preview_job_id_key`(`preview_job_id`), + UNIQUE INDEX `outbound_import_session_import_job_id_key`(`import_job_id`), INDEX `outbound_import_session_status_idx`(`status`), INDEX `outbound_import_session_created_by_idx`(`created_by`), INDEX `outbound_import_session_expires_at_idx`(`expires_at`), @@ -304,9 +414,6 @@ CREATE TABLE `outbound_import_row` ( `out_time` DATETIME(3) NULL, `out_image_paths` JSON NULL, `out_image_keys` JSON NULL, - `tx_hash` VARCHAR(191) NULL, - `onchain_at` DATETIME(3) NULL, - `block_height` BIGINT NULL, `remark` VARCHAR(191) NULL, `reason` TEXT NULL, `preview` JSON NULL, @@ -387,11 +494,47 @@ ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_batch_id_fkey` FOREIGN KEY ( ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_group_id_fkey` FOREIGN KEY (`group_id`) REFERENCES `trace_code_group`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; -- AddForeignKey -ALTER TABLE `blockchain_proof` ADD CONSTRAINT `blockchain_proof_trace_code_id_fkey` FOREIGN KEY (`trace_code_id`) REFERENCES `trace_code`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE `blockchain_proof` ADD CONSTRAINT `blockchain_proof_trace_code_id_fkey` FOREIGN KEY (`trace_code_id`) REFERENCES `trace_code`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `blockchain_proof` ADD CONSTRAINT `blockchain_proof_onchain_chunk_id_fkey` FOREIGN KEY (`onchain_chunk_id`) REFERENCES `onchain_chunk`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; -- AddForeignKey ALTER TABLE `query_log` ADD CONSTRAINT `query_log_trace_code_id_fkey` FOREIGN KEY (`trace_code_id`) REFERENCES `trace_code`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; +-- AddForeignKey +ALTER TABLE `job_item` ADD CONSTRAINT `job_item_job_id_fkey` FOREIGN KEY (`job_id`) REFERENCES `job`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `job_item` ADD CONSTRAINT `job_item_trace_code_id_fkey` FOREIGN KEY (`trace_code_id`) REFERENCES `trace_code`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `job_item` ADD CONSTRAINT `job_item_proof_id_fkey` FOREIGN KEY (`proof_id`) REFERENCES `blockchain_proof`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `job_item` ADD CONSTRAINT `job_item_chunk_id_fkey` FOREIGN KEY (`chunk_id`) REFERENCES `onchain_chunk`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `onchain_chunk` ADD CONSTRAINT `onchain_chunk_job_id_fkey` FOREIGN KEY (`job_id`) REFERENCES `job`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `onchain_chunk` ADD CONSTRAINT `onchain_chunk_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `outbound_record` ADD CONSTRAINT `outbound_record_trace_code_id_fkey` FOREIGN KEY (`trace_code_id`) REFERENCES `trace_code`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `outbound_record` ADD CONSTRAINT `outbound_record_created_by_fkey` FOREIGN KEY (`created_by`) REFERENCES `sys_user`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `outbound_record` ADD CONSTRAINT `outbound_record_updated_by_fkey` FOREIGN KEY (`updated_by`) REFERENCES `sys_user`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `outbound_image` ADD CONSTRAINT `outbound_image_outbound_record_id_fkey` FOREIGN KEY (`outbound_record_id`) REFERENCES `outbound_record`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `outbound_image` ADD CONSTRAINT `outbound_image_created_by_fkey` FOREIGN KEY (`created_by`) REFERENCES `sys_user`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + -- AddForeignKey ALTER TABLE `operation_log` ADD CONSTRAINT `operation_log_user_id_fkey` FOREIGN KEY (`user_id`) REFERENCES `sys_user`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; @@ -403,4 +546,3 @@ ALTER TABLE `outbound_import_row` ADD CONSTRAINT `outbound_import_row_session_id -- AddForeignKey ALTER TABLE `backup_record` ADD CONSTRAINT `backup_record_created_by_fkey` FOREIGN KEY (`created_by`) REFERENCES `sys_user`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; - diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 3d970c6..cb19020 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -82,9 +82,11 @@ enum TraceCodeStatus { enum ProofStatus { PENDING + SUBMITTING CONFIRMING ONCHAIN FAILED + UNKNOWN } enum QueryResult { @@ -99,6 +101,7 @@ enum JobType { GEN_CODE IMPORT_OUTBOUND IMPORT_OUTBOUND_PREVIEW + BATCH_OUTBOUND WATERMARK ONCHAIN BACKUP @@ -113,6 +116,25 @@ enum JobStatus { FAILED } +enum JobItemStatus { + PENDING + PROCESSING + SUCCESS + FAILED + SKIPPED + UNKNOWN +} + +enum OnchainChunkStatus { + PENDING + SUBMITTING + CONFIRMING + SUCCESS + PARTIAL + FAILED + UNKNOWN +} + enum OutboundImportSessionStatus { PARSING READY @@ -148,12 +170,15 @@ model SysUser { createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") - artworks Artwork[] - operationLogs OperationLog[] - outboundImportSessions OutboundImportSession[] - backupRecords BackupRecord[] - submittedArtworkRevisions ArtworkRevision[] @relation("ArtworkRevisionSubmitter") - reviewedArtworkRevisions ArtworkRevision[] @relation("ArtworkRevisionReviewer") + artworks Artwork[] + operationLogs OperationLog[] + outboundImportSessions OutboundImportSession[] + backupRecords BackupRecord[] + submittedArtworkRevisions ArtworkRevision[] @relation("ArtworkRevisionSubmitter") + reviewedArtworkRevisions ArtworkRevision[] @relation("ArtworkRevisionReviewer") + createdOutboundRecords OutboundRecord[] @relation("OutboundRecordCreator") + updatedOutboundRecords OutboundRecord[] @relation("OutboundRecordUpdater") + uploadedOutboundImages OutboundImage[] @relation("OutboundImageUploader") @@map("sys_user") } @@ -206,13 +231,14 @@ model Artwork { updatedAt DateTime @updatedAt @map("updated_at") deletedAt DateTime? @map("deleted_at") - template Template @relation(fields: [templateId], references: [id]) - creator SysUser? @relation(fields: [createdBy], references: [id]) - traceNodes TraceNode[] - certificates Certificate[] - batches Batch[] - traceCodes TraceCode[] - revisions ArtworkRevision[] + template Template @relation(fields: [templateId], references: [id]) + creator SysUser? @relation(fields: [createdBy], references: [id]) + traceNodes TraceNode[] + certificates Certificate[] + batches Batch[] + traceCodes TraceCode[] + revisions ArtworkRevision[] + onchainChunks OnchainChunk[] @@index([templateId]) @@index([status]) @@ -228,7 +254,7 @@ model ArtworkRevision { beforeSnapshot Json @map("before_snapshot") afterSnapshot Json @map("after_snapshot") status ArtworkRevisionStatus @default(PENDING) - auditRemark String? @db.Text @map("audit_remark") + auditRemark String? @map("audit_remark") @db.Text submittedBy Int? @map("submitted_by") submittedAt DateTime @default(now()) @map("submitted_at") reviewedBy Int? @map("reviewed_by") @@ -309,12 +335,10 @@ model Batch { model TraceCode { id BigInt @id @default(autoincrement()) shortCode String @unique @map("short_code") + serialNo Int @unique @map("serial_no") artworkId Int @map("artwork_id") batchId Int @map("batch_id") groupId Int? @map("group_id") - outTime DateTime? @map("out_time") - outImages Json? @map("out_images") - remark String? status TraceCodeStatus @default(INACTIVE) queryCount Int @default(0) @map("query_count") firstActivatedAt DateTime? @map("first_activated_at") @@ -327,6 +351,8 @@ model TraceCode { group TraceCodeGroup? @relation(fields: [groupId], references: [id]) proofs BlockchainProof[] queryLogs QueryLog[] + outbound OutboundRecord? + jobItems JobItem[] @@index([artworkId]) @@index([batchId]) @@ -335,12 +361,12 @@ model TraceCode { @@map("trace_code") } -model TraceCodeDailySequence { - dateKey String @id @map("date_key") @db.VarChar(6) - nextSeq Int @default(0) @map("next_seq") +model TraceCodeSequence { + id Int @id + nextSeq Int @default(1) @map("next_seq") updatedAt DateTime @updatedAt @map("updated_at") - @@map("trace_code_daily_sequence") + @@map("trace_code_sequence") } model BlockchainProof { @@ -354,14 +380,23 @@ model BlockchainProof { explorerUrl String? @map("explorer_url") tokenId BigInt? @map("token_id") contractAddress String? @map("contract_address") + submittedAt DateTime? @map("submitted_at") onchainAt DateTime? @map("onchain_at") status ProofStatus @default(PENDING) + onchainChunkId String? @map("onchain_chunk_id") + failureReason String? @map("failure_reason") @db.Text + lastSyncedAt DateTime? @map("last_synced_at") rawResponse Json? @map("raw_response") createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") - traceCode TraceCode @relation(fields: [traceCodeId], references: [id], onDelete: Cascade) + traceCode TraceCode @relation(fields: [traceCodeId], references: [id], onDelete: Restrict) + onchainChunk OnchainChunk? @relation(fields: [onchainChunkId], references: [id], onDelete: SetNull) + jobItems JobItem[] - @@index([traceCodeId]) + @@unique([traceCodeId]) + @@index([status]) + @@index([onchainChunkId]) @@map("blockchain_proof") } @@ -377,7 +412,7 @@ model QueryLog { queriedAt DateTime @default(now()) @map("queried_at") queryResult QueryResult @map("query_result") ip String? - userAgent String? @db.Text @map("user_agent") + userAgent String? @map("user_agent") @db.Text deviceType String? @map("device_type") browser String? os String? @@ -405,26 +440,134 @@ model Job { createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") + items JobItem[] + onchainChunks OnchainChunk[] + + @@index([type]) + @@index([status]) @@map("job") } +model JobItem { + id BigInt @id @default(autoincrement()) + jobId String @map("job_id") + traceCodeId BigInt? @map("trace_code_id") + selectionKey String @map("selection_key") + proofId Int? @map("proof_id") + chunkId String? @map("chunk_id") + sequence Int @default(0) + shortCode String @map("short_code") + status JobItemStatus @default(PENDING) + payload Json? + result Json? + error String? @db.Text + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + job Job @relation(fields: [jobId], references: [id], onDelete: Cascade) + traceCode TraceCode? @relation(fields: [traceCodeId], references: [id], onDelete: Restrict) + proof BlockchainProof? @relation(fields: [proofId], references: [id], onDelete: SetNull) + chunk OnchainChunk? @relation(fields: [chunkId], references: [id], onDelete: SetNull) + + @@unique([jobId, selectionKey]) + @@index([jobId, status]) + @@index([chunkId, status]) + @@index([traceCodeId]) + @@index([proofId]) + @@map("job_item") +} + +model OnchainChunk { + id String @id @default(cuid()) + jobId String @map("job_id") + artworkId Int @map("artwork_id") + sequenceNo Int @map("sequence_no") + status OnchainChunkStatus @default(PENDING) + operateId String @unique @map("operate_id") @db.VarChar(20) + runToken String? @map("run_token") + productIds Json @map("product_ids") + metadataSnapshot Json @map("metadata_snapshot") + requestPayload Json @map("request_payload") + response Json? + txHash String? @map("tx_hash") + contractAddress String? @map("contract_address") + baseTokenId BigInt? @map("base_token_id") + failureReason String? @map("failure_reason") @db.Text + attemptCount Int @default(0) @map("attempt_count") + submittedAt DateTime? @map("submitted_at") + unknownAt DateTime? @map("unknown_at") + confirmedAt DateTime? @map("confirmed_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + job Job @relation(fields: [jobId], references: [id], onDelete: Cascade) + artwork Artwork @relation(fields: [artworkId], references: [id], onDelete: Restrict) + proofs BlockchainProof[] + items JobItem[] + + @@unique([jobId, sequenceNo]) + @@index([status]) + @@index([status, updatedAt]) + @@index([artworkId]) + @@map("onchain_chunk") +} + +model OutboundRecord { + id BigInt @id @default(autoincrement()) + traceCodeId BigInt @unique @map("trace_code_id") + outTime DateTime @map("out_time") + remark String? @db.Text + createdBy Int? @map("created_by") + updatedBy Int? @map("updated_by") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + traceCode TraceCode @relation(fields: [traceCodeId], references: [id], onDelete: Restrict) + creator SysUser? @relation("OutboundRecordCreator", fields: [createdBy], references: [id], onDelete: SetNull) + updater SysUser? @relation("OutboundRecordUpdater", fields: [updatedBy], references: [id], onDelete: SetNull) + images OutboundImage[] + + @@index([outTime]) + @@map("outbound_record") +} + +model OutboundImage { + id BigInt @id @default(autoincrement()) + outboundRecordId BigInt @map("outbound_record_id") + fileKey String @unique @map("file_key") @db.VarChar(512) + fileName String @map("file_name") + mimeType String @map("mime_type") + size BigInt + width Int + height Int + sortOrder Int @default(0) @map("sort_order") + createdBy Int? @map("created_by") + createdAt DateTime @default(now()) @map("created_at") + + outboundRecord OutboundRecord @relation(fields: [outboundRecordId], references: [id], onDelete: Cascade) + uploader SysUser? @relation("OutboundImageUploader", fields: [createdBy], references: [id], onDelete: SetNull) + + @@index([outboundRecordId, sortOrder]) + @@map("outbound_image") +} + model OperationLog { - id BigInt @id @default(autoincrement()) - userId Int? @map("user_id") + id BigInt @id @default(autoincrement()) + userId Int? @map("user_id") username String? role RoleType? module String action String method String - path String @db.VarChar(512) - targetId String? @map("target_id") + path String @db.VarChar(512) + targetId String? @map("target_id") status String - message String? @db.Text + message String? @db.Text ip String? - userAgent String? @db.Text @map("user_agent") - durationMs Int? @map("duration_ms") - requestSummary Json? @map("request_summary") - createdAt DateTime @default(now()) @map("created_at") + userAgent String? @map("user_agent") @db.Text + durationMs Int? @map("duration_ms") + requestSummary Json? @map("request_summary") + createdAt DateTime @default(now()) @map("created_at") user SysUser? @relation(fields: [userId], references: [id]) @@ -455,7 +598,7 @@ model OutboundImportSession { createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") - creator SysUser? @relation(fields: [createdBy], references: [id]) + creator SysUser? @relation(fields: [createdBy], references: [id]) rows OutboundImportRow[] @@index([status]) @@ -465,19 +608,19 @@ model OutboundImportSession { } model OutboundImportRow { - id BigInt @id @default(autoincrement()) - sessionId String @map("session_id") - rowNo Int @map("row_no") - status OutboundImportRowStatus @default(INVALID) - shortCode String? @map("short_code") - batchNo String? @map("batch_no") - outTime DateTime? @map("out_time") - outImagePaths Json? @map("out_image_paths") - outImageKeys Json? @map("out_image_keys") - remark String? - reason String? @db.Text - preview Json? - createdAt DateTime @default(now()) @map("created_at") + id BigInt @id @default(autoincrement()) + sessionId String @map("session_id") + rowNo Int @map("row_no") + status OutboundImportRowStatus @default(INVALID) + shortCode String? @map("short_code") + batchNo String? @map("batch_no") + outTime DateTime? @map("out_time") + outImagePaths Json? @map("out_image_paths") + outImageKeys Json? @map("out_image_keys") + remark String? + reason String? @db.Text + preview Json? + createdAt DateTime @default(now()) @map("created_at") session OutboundImportSession @relation(fields: [sessionId], references: [id], onDelete: Cascade) diff --git a/apps/api/prisma/seed.ts b/apps/api/prisma/seed.ts index 3eb85f9..d7ad793 100644 --- a/apps/api/prisma/seed.ts +++ b/apps/api/prisma/seed.ts @@ -3,7 +3,7 @@ import * as bcrypt from 'bcryptjs'; import { existsSync, mkdirSync, writeFileSync } from 'fs'; import { dirname, join, resolve } from 'path'; import { customAlphabet } from 'nanoid'; -import { randomBytes, createHash } from 'crypto'; +import { randomBytes, randomInt, createHash } from 'crypto'; import sharp from 'sharp'; import { addWatermark } from '../src/certificate/watermark.util'; @@ -11,15 +11,9 @@ const prisma = new PrismaClient(); const storageDir = resolve(process.env.STORAGE_LOCAL_DIR || './storage'); const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; const shortId = customAlphabet(ALPHABET, 10); -// 公开短码须为 12 位纯数字(与 TRACE_CODE_PATTERN=/^\d{12}$/ 一致),否则 C 端公开溯源会判 INVALID -const numericId = customAlphabet('0123456789', 12); -function uniqueShortCode(used: Set): string { - let code = numericId(); - while (used.has(code)) code = numericId(); - used.add(code); - return code; +function buildShortCode(serialNo: number): string { + return `${randomInt(0, 1_000_000).toString().padStart(6, '0')}${serialNo.toString().padStart(6, '0')}`; } -const usedShortCodes = new Set(); const watermarkText = process.env.WATERMARK_TEXT || '仅供溯源核验使用'; const DEFAULT_TEMPLATE_FIELDS = [ { fieldKey: 'craft', label: '工艺', type: 'TEXT', required: true, sortOrder: 0 }, @@ -68,7 +62,7 @@ async function ensureUsers(): Promise { role: u.role, }, }); - console.log(`已创建用户:${u.username} / ${u.password}(${u.role})`); + console.log(`已创建用户:${u.username}(${u.role})`); } } } @@ -216,11 +210,13 @@ async function ensureSampleData(): Promise { const artworkActive = artworkSeq < 2; // 前两款带激活码与查询记录 for (let k = 0; k < CODES_PER_ARTWORK; k++) { - const shortCode = uniqueShortCode(usedShortCodes); + const serialNo = totalCodes + 1; + const shortCode = buildShortCode(serialNo); const isActive = artworkActive && k < 2; // 该款前两套已激活 const code = await prisma.traceCode.create({ data: { shortCode, + serialNo, artworkId: artwork.id, batchId: batch.id, url: `${base}/t/${shortCode}`, @@ -273,6 +269,11 @@ async function ensureSampleData(): Promise { } artworkSeq++; } + await prisma.traceCodeSequence.upsert({ + where: { id: 1 }, + update: { nextSeq: totalCodes + 1 }, + create: { id: 1, nextSeq: totalCodes + 1 }, + }); console.log(`已创建示例:模板 1、作品 ${samples.length}(每款 ${CODES_PER_ARTWORK} 码,共 ${totalCodes} 码)、证书、查询日志与存证。`); } diff --git a/apps/api/src/artwork/artwork.controller.ts b/apps/api/src/artwork/artwork.controller.ts index dfc6d96..806552c 100644 --- a/apps/api/src/artwork/artwork.controller.ts +++ b/apps/api/src/artwork/artwork.controller.ts @@ -52,7 +52,7 @@ export class ArtworkController { @Roles(RoleType.OPERATOR) @ApiOperation({ summary: '创建艺术品档案' }) create(@Body() dto: CreateArtworkDto, @CurrentUser() user: AuthUser) { - return this.artworkService.create(dto, user.id); + return this.artworkService.create(dto, user); } @Put(':id') diff --git a/apps/api/src/artwork/artwork.service.spec.ts b/apps/api/src/artwork/artwork.service.spec.ts new file mode 100644 index 0000000..233f818 --- /dev/null +++ b/apps/api/src/artwork/artwork.service.spec.ts @@ -0,0 +1,352 @@ +import { ArtworkRevisionStatus, ArtworkStatus, AuditStatus, RoleType } from '@artveris/shared'; +import type { AuthUser } from '../common/decorators/current-user.decorator'; +import { CertificateController } from '../certificate/certificate.controller'; +import { TraceNodeController } from '../trace-node/trace-node.controller'; +import { ArtworkController } from './artwork.controller'; +import { ArtworkService } from './artwork.service'; + +function user(role: RoleType, id = 9): AuthUser { + return { id, username: role.toLowerCase(), role }; +} + +function createHarness() { + const tx = { + artwork: { + create: jest.fn().mockImplementation(({ data }) => ({ + id: 7, + templateId: data.templateId, + title: data.title, + artist: data.artist ?? null, + status: data.status, + auditStatus: data.auditStatus, + dynamicFields: data.dynamicFields, + images: data.images, + traceNodes: [], + certificates: [], + })), + update: jest.fn().mockResolvedValue(undefined), + }, + artworkRevision: { + create: jest.fn().mockResolvedValue({ id: 'revision-create' }), + }, + }; + const prisma = { + template: { findFirst: jest.fn().mockResolvedValue({ id: 1 }) }, + $transaction: jest.fn().mockImplementation(async (callback: any) => callback(tx)), + }; + const service = new ArtworkService(prisma as any, {} as any, {} as any); + jest.spyOn(service as any, 'relocateArtworkMedia').mockResolvedValue(new Map()); + const enqueueWatermarks = jest + .spyOn(service as any, 'enqueuePendingCertificateWatermarks') + .mockResolvedValue(undefined); + jest.spyOn(service, 'get').mockResolvedValue({ id: 7 } as any); + return { service, tx, enqueueWatermarks }; +} + +describe('ArtworkService.create approval policy', () => { + it.each([ArtworkStatus.ACTIVE, ArtworkStatus.DRAFT])( + 'auto-approves a super-admin %s creation and records the same submitter and reviewer', + async (status) => { + const { service, tx, enqueueWatermarks } = createHarness(); + + await service.create({ templateId: 1, title: '测试作品', status } as any, user(RoleType.SUPER_ADMIN)); + + expect(tx.artwork.create).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + status, + auditStatus: AuditStatus.APPROVED, + auditRemark: '超级管理员操作,自动审批通过', + createdBy: 9, + auditedBy: 9, + auditedAt: expect.any(Date), + }), + }), + ); + expect(tx.artworkRevision.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + artworkId: 7, + status: ArtworkRevisionStatus.APPROVED, + auditRemark: '超级管理员操作,自动审批通过', + submittedBy: 9, + submittedAt: expect.any(Date), + reviewedBy: 9, + reviewedAt: expect.any(Date), + }), + }); + expect(enqueueWatermarks).toHaveBeenCalledWith(7); + }, + ); + + it('keeps an operator active creation pending without a reviewer', async () => { + const { service, tx } = createHarness(); + + await service.create( + { templateId: 1, title: '待审作品', status: ArtworkStatus.ACTIVE } as any, + user(RoleType.OPERATOR), + ); + + expect(tx.artwork.create).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + auditStatus: AuditStatus.PENDING, + auditedBy: null, + auditedAt: null, + }), + }), + ); + expect(tx.artworkRevision.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + status: ArtworkRevisionStatus.PENDING, + submittedBy: 9, + submittedAt: undefined, + reviewedBy: null, + reviewedAt: null, + }), + }); + }); +}); + +function updateHarness() { + const current = { + artwork: { + templateId: 1, + title: '修改前', + artist: null, + status: ArtworkStatus.ACTIVE, + dynamicFields: {}, + images: [], + }, + traceNodes: [], + certificates: [], + }; + const tx = { + artworkRevision: { + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + create: jest.fn().mockResolvedValue({ id: 'revision-update' }), + update: jest.fn().mockResolvedValue(undefined), + }, + }; + const prisma = { + $transaction: jest.fn().mockImplementation(async (callback: any) => callback(tx)), + }; + const service = new ArtworkService(prisma as any, {} as any, {} as any); + jest.spyOn(service as any, 'ensureExists').mockResolvedValue({ + id: 7, + templateId: 1, + archiveNo: null, + status: ArtworkStatus.ACTIVE, + auditStatus: AuditStatus.APPROVED, + }); + jest.spyOn(service as any, 'relocateArtworkMedia').mockResolvedValue(new Map()); + const getSnapshot = jest.spyOn(service as any, 'getSnapshot').mockResolvedValue(current); + const applySnapshot = jest.spyOn(service as any, 'applySnapshot').mockResolvedValue(undefined); + const enqueueWatermarks = jest + .spyOn(service as any, 'enqueuePendingCertificateWatermarks') + .mockResolvedValue(undefined); + jest.spyOn(service, 'get').mockResolvedValue({ id: 7 } as any); + return { service, tx, applySnapshot, enqueueWatermarks, getSnapshot }; +} + +describe('ArtworkService.update approval policy', () => { + it('applies a super-admin revision immediately and records who superseded the pending revision', async () => { + const { service, tx, applySnapshot, enqueueWatermarks } = updateHarness(); + + await service.update(7, { title: '修改后' } as any, user(RoleType.SUPER_ADMIN)); + + expect(tx.artworkRevision.updateMany).toHaveBeenCalledWith({ + where: { artworkId: 7, status: ArtworkRevisionStatus.PENDING }, + data: { + status: ArtworkRevisionStatus.REJECTED, + auditRemark: '已被新的修改提交替代', + reviewedBy: 9, + reviewedAt: expect.any(Date), + }, + }); + expect(tx.artworkRevision.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + status: ArtworkRevisionStatus.APPROVED, + auditRemark: '超级管理员操作,自动审批通过', + reason: '超级管理员修改作品,自动审批通过', + submittedBy: 9, + submittedAt: expect.any(Date), + reviewedBy: 9, + reviewedAt: expect.any(Date), + }), + }); + expect(applySnapshot).toHaveBeenCalledWith( + tx, + 7, + expect.objectContaining({ artwork: expect.objectContaining({ title: '修改后' }) }), + { + auditStatus: AuditStatus.APPROVED, + auditRemark: '超级管理员操作,自动审批通过', + auditedBy: 9, + auditedAt: expect.any(Date), + }, + ); + expect(enqueueWatermarks).toHaveBeenCalledWith(7); + }); + + it('keeps an operator revision pending and does not overwrite an approved formal version', async () => { + const { service, tx, applySnapshot } = updateHarness(); + + await service.update(7, { title: '运营修改' } as any, user(RoleType.OPERATOR)); + + expect(tx.artworkRevision.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + status: ArtworkRevisionStatus.PENDING, + submittedBy: 9, + reviewedBy: null, + reviewedAt: null, + }), + }); + expect(applySnapshot).not.toHaveBeenCalled(); + }); + + it('activates a super-admin draft immediately without entering the pending queue', async () => { + const { service, tx, applySnapshot, getSnapshot } = updateHarness(); + (service as any).ensureExists.mockResolvedValue({ + id: 7, + templateId: 1, + archiveNo: null, + status: ArtworkStatus.DRAFT, + auditStatus: AuditStatus.APPROVED, + }); + getSnapshot.mockResolvedValue({ + artwork: { + templateId: 1, + title: '草稿作品', + artist: null, + status: ArtworkStatus.DRAFT, + dynamicFields: {}, + images: [], + }, + traceNodes: [], + certificates: [], + }); + + await service.update( + 7, + { title: '启用作品', status: ArtworkStatus.ACTIVE } as any, + user(RoleType.SUPER_ADMIN), + ); + + expect(tx.artworkRevision.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ status: ArtworkRevisionStatus.APPROVED }), + }); + expect(applySnapshot).toHaveBeenCalledWith( + tx, + 7, + expect.objectContaining({ artwork: expect.objectContaining({ status: ArtworkStatus.ACTIVE }) }), + expect.objectContaining({ auditStatus: AuditStatus.APPROVED, auditedBy: 9 }), + ); + }); +}); + +describe('ArtworkService.audit approval boundary', () => { + function auditHarness(claimCount = 1) { + const revision = { + id: 'revision-pending', + artworkId: 7, + status: ArtworkRevisionStatus.PENDING, + afterSnapshot: { + artwork: { + templateId: 1, + title: '审核后作品', + artist: null, + status: ArtworkStatus.ACTIVE, + dynamicFields: {}, + images: [], + }, + traceNodes: [], + certificates: [], + }, + }; + const tx = { + artworkRevision: { updateMany: jest.fn().mockResolvedValue({ count: claimCount }) }, + artwork: { update: jest.fn() }, + }; + const prisma = { + artworkRevision: { findFirst: jest.fn().mockResolvedValue(revision) }, + $transaction: jest.fn().mockImplementation(async (callback: any) => callback(tx)), + }; + const service = new ArtworkService(prisma as any, {} as any, {} as any); + jest.spyOn(service as any, 'ensureExists').mockResolvedValue({ + id: 7, + status: ArtworkStatus.ACTIVE, + auditStatus: AuditStatus.PENDING, + }); + const applySnapshot = jest.spyOn(service as any, 'applySnapshot').mockResolvedValue(undefined); + jest.spyOn(service as any, 'enqueuePendingCertificateWatermarks').mockResolvedValue(undefined); + jest.spyOn(service, 'get').mockResolvedValue({ id: 7 } as any); + return { service, prisma, tx, applySnapshot }; + } + + it('allows an auditor to approve an operator pending revision exactly once', async () => { + const { service, tx, applySnapshot } = auditHarness(); + + await service.audit(7, { approved: true, remark: '审核通过' } as any, 12); + + expect(tx.artworkRevision.updateMany).toHaveBeenCalledWith({ + where: { id: 'revision-pending', status: ArtworkRevisionStatus.PENDING }, + data: expect.objectContaining({ + status: ArtworkRevisionStatus.APPROVED, + reviewedBy: 12, + auditRemark: '审核通过', + }), + }); + expect(applySnapshot).toHaveBeenCalledWith( + tx, + 7, + expect.any(Object), + expect.objectContaining({ auditStatus: AuditStatus.APPROVED, auditedBy: 12 }), + ); + }); + + it('rejects an audit when no pending revision exists', async () => { + const { service, prisma } = auditHarness(); + prisma.artworkRevision.findFirst.mockResolvedValue(null); + + await expect(service.audit(7, { approved: false } as any, 12)).rejects.toThrow( + '该作品没有待审核的修改记录', + ); + }); + + it('rejects a concurrent second review when the pending revision was already claimed', async () => { + const { service, applySnapshot } = auditHarness(0); + + await expect(service.audit(7, { approved: true } as any, 12)).rejects.toThrow( + '该修改记录已审核,不能重复操作', + ); + expect(applySnapshot).not.toHaveBeenCalled(); + }); +}); + +describe('ArtworkController.create', () => { + it('passes the complete authenticated user to the service for role-based approval', () => { + const service = { create: jest.fn() }; + const controller = new ArtworkController(service as any); + const admin = user(RoleType.SUPER_ADMIN); + const dto = { templateId: 1, title: '测试作品' } as any; + + controller.create(dto, admin); + + expect(service.create).toHaveBeenCalledWith(dto, admin); + }); +}); + +describe('Artwork content write boundary', () => { + it('does not expose trace-node writes outside the artwork snapshot endpoint', () => { + expect((TraceNodeController.prototype as any).create).toBeUndefined(); + expect((TraceNodeController.prototype as any).update).toBeUndefined(); + expect((TraceNodeController.prototype as any).remove).toBeUndefined(); + expect((TraceNodeController.prototype as any).reorder).toBeUndefined(); + }); + + it('does not expose certificate writes outside the artwork snapshot endpoint', () => { + expect((CertificateController.prototype as any).create).toBeUndefined(); + expect((CertificateController.prototype as any).update).toBeUndefined(); + expect((CertificateController.prototype as any).remove).toBeUndefined(); + }); +}); diff --git a/apps/api/src/artwork/artwork.service.ts b/apps/api/src/artwork/artwork.service.ts index e4f08f6..6a12b6b 100644 --- a/apps/api/src/artwork/artwork.service.ts +++ b/apps/api/src/artwork/artwork.service.ts @@ -19,6 +19,8 @@ import { } from './dto/artwork.dto'; import type { AuthUser } from '../common/decorators/current-user.decorator'; +const AUTO_APPROVAL_REMARK = '超级管理员操作,自动审批通过'; + interface MediaItem { key: string; name?: string; @@ -158,7 +160,10 @@ export class ArtworkService { }); } - async create(dto: CreateArtworkDto, userId: number) { + async create(dto: CreateArtworkDto, user: AuthUser) { + const userId = user.id; + const shouldAutoApprove = user.role === RoleType.SUPER_ADMIN; + const reviewedAt = shouldAutoApprove ? new Date() : null; const tpl = await this.prisma.template.findFirst({ where: { id: dto.templateId, deletedAt: null }, }); @@ -176,7 +181,10 @@ export class ArtworkService { title: dto.title, artist: dto.artist, status, - auditStatus: AuditStatus.PENDING, + auditStatus: shouldAutoApprove ? AuditStatus.APPROVED : AuditStatus.PENDING, + auditRemark: shouldAutoApprove ? AUTO_APPROVAL_REMARK : null, + auditedBy: shouldAutoApprove ? userId : null, + auditedAt: reviewedAt, dynamicFields: (dto.dynamicFields ?? {}) as Prisma.InputJsonValue, images: (dto.images ?? []) as unknown as Prisma.InputJsonValue, createdBy: userId, @@ -214,12 +222,31 @@ export class ArtworkService { const revision = await tx.artworkRevision.create({ data: { artworkId: created.id, - title: status === ArtworkStatus.DRAFT ? '创建草稿' : '提交初次审核', - reason: status === ArtworkStatus.DRAFT ? '新建作品保存为草稿' : '新建作品提交审核', + title: + status === ArtworkStatus.DRAFT + ? '创建草稿' + : shouldAutoApprove + ? '创建作品' + : '提交初次审核', + reason: + status === ArtworkStatus.DRAFT + ? shouldAutoApprove + ? '超级管理员创建草稿,自动审核通过' + : '新建作品保存为草稿' + : shouldAutoApprove + ? '超级管理员创建作品,自动审核通过' + : '新建作品提交审核', beforeSnapshot: {} as Prisma.InputJsonObject, afterSnapshot: snapshot as unknown as Prisma.InputJsonObject, - status: status === ArtworkStatus.DRAFT ? ArtworkRevisionStatus.APPROVED : ArtworkRevisionStatus.PENDING, + status: + status === ArtworkStatus.DRAFT || shouldAutoApprove + ? ArtworkRevisionStatus.APPROVED + : ArtworkRevisionStatus.PENDING, + auditRemark: shouldAutoApprove ? AUTO_APPROVAL_REMARK : null, submittedBy: userId, + submittedAt: reviewedAt ?? undefined, + reviewedBy: shouldAutoApprove ? userId : null, + reviewedAt, }, }); return { created, revisionId: revision.id }; @@ -414,14 +441,16 @@ export class ArtworkService { }; const shouldApplyDirectly = artwork.status !== ArtworkStatus.ACTIVE || artwork.auditStatus !== AuditStatus.APPROVED; const shouldAutoApprove = user.role === RoleType.SUPER_ADMIN; + const reviewedAt = shouldAutoApprove ? new Date() : null; if (!this.hasSnapshotChanged(current, afterSnapshot)) { throw new BusinessException(ErrorCode.VALIDATION_FAILED, '作品内容未发生变化,无需提交审核', 400); } const revisionTitle = dto.revisionTitle || '作品内容修改'; - const revisionReason = dto.revisionReason || null; + const revisionReason = + dto.revisionReason || (shouldAutoApprove ? '超级管理员修改作品,自动审批通过' : null); await this.prisma.$transaction(async (tx) => { - await this.supersedePendingRevisions(tx, id); + await this.supersedePendingRevisions(tx, id, userId); const revision = await tx.artworkRevision.create({ data: { artworkId: id, @@ -430,19 +459,20 @@ export class ArtworkService { beforeSnapshot: current as unknown as Prisma.InputJsonObject, afterSnapshot: afterSnapshot as unknown as Prisma.InputJsonObject, status: shouldAutoApprove ? ArtworkRevisionStatus.APPROVED : ArtworkRevisionStatus.PENDING, - auditRemark: null, + auditRemark: shouldAutoApprove ? AUTO_APPROVAL_REMARK : null, submittedBy: userId, + submittedAt: reviewedAt ?? undefined, reviewedBy: shouldAutoApprove ? userId : null, - reviewedAt: shouldAutoApprove ? new Date() : null, + reviewedAt, }, }); if (shouldAutoApprove || shouldApplyDirectly) { await this.applySnapshot(tx, id, afterSnapshot, { auditStatus: shouldAutoApprove ? AuditStatus.APPROVED : AuditStatus.PENDING, - auditRemark: null, + auditRemark: shouldAutoApprove ? AUTO_APPROVAL_REMARK : null, auditedBy: shouldAutoApprove ? userId : null, - auditedAt: shouldAutoApprove ? new Date() : null, + auditedAt: reviewedAt, }); await tx.artworkRevision.update({ where: { id: revision.id }, data: { afterSnapshot: afterSnapshot as unknown as Prisma.InputJsonObject } }); } @@ -561,20 +591,10 @@ export class ArtworkService { orderBy: { submittedAt: 'desc' }, }); - if (revision) { - await this.auditRevision(id, revision.id, dto, auditorId); - return this.get(id); + if (!revision) { + throw new BusinessException(ErrorCode.VALIDATION_FAILED, '该作品没有待审核的修改记录', 400); } - - await this.prisma.artwork.update({ - where: { id }, - data: { - auditStatus: dto.approved ? AuditStatus.APPROVED : AuditStatus.REJECTED, - auditRemark: dto.remark ?? null, - auditedBy: auditorId, - auditedAt: new Date(), - }, - }); + await this.auditRevision(id, revision.id, dto, auditorId); return this.get(id); } @@ -840,12 +860,13 @@ export class ArtworkService { } } - private async supersedePendingRevisions(tx: Prisma.TransactionClient, artworkId: number) { + private async supersedePendingRevisions(tx: Prisma.TransactionClient, artworkId: number, actorId: number) { await tx.artworkRevision.updateMany({ where: { artworkId, status: ArtworkRevisionStatus.PENDING }, data: { status: ArtworkRevisionStatus.REJECTED, auditRemark: '已被新的修改提交替代', + reviewedBy: actorId, reviewedAt: new Date(), }, }); @@ -855,37 +876,29 @@ export class ArtworkService { const artwork = await this.ensureExists(id); const revision = await this.prisma.artworkRevision.findFirst({ where: { id: revisionId, artworkId: id } }); if (!revision) throw new BusinessException(ErrorCode.NOT_FOUND, '修改记录不存在', 404); - if (revision.status !== ArtworkRevisionStatus.PENDING) { - throw new BusinessException(ErrorCode.VALIDATION_FAILED, '该修改记录已审核,不能重复操作', 400); - } - await this.prisma.$transaction(async (tx) => { + const reviewedAt = new Date(); + const claimed = await tx.artworkRevision.updateMany({ + where: { id: revisionId, status: ArtworkRevisionStatus.PENDING }, + data: { + status: dto.approved ? ArtworkRevisionStatus.APPROVED : ArtworkRevisionStatus.REJECTED, + auditRemark: dto.remark ?? null, + reviewedBy: auditorId, + reviewedAt, + }, + }); + if (claimed.count !== 1) { + throw new BusinessException(ErrorCode.VALIDATION_FAILED, '该修改记录已审核,不能重复操作', 400); + } + if (dto.approved) { await this.applySnapshot(tx, id, revision.afterSnapshot as unknown as ArtworkSnapshot, { auditStatus: AuditStatus.APPROVED, auditRemark: dto.remark ?? null, auditedBy: auditorId, - auditedAt: new Date(), - }); - await tx.artworkRevision.update({ - where: { id: revisionId }, - data: { - status: ArtworkRevisionStatus.APPROVED, - auditRemark: dto.remark ?? null, - reviewedBy: auditorId, - reviewedAt: new Date(), - }, + auditedAt: reviewedAt, }); } else { - await tx.artworkRevision.update({ - where: { id: revisionId }, - data: { - status: ArtworkRevisionStatus.REJECTED, - auditRemark: dto.remark ?? null, - reviewedBy: auditorId, - reviewedAt: new Date(), - }, - }); if (artwork.auditStatus !== AuditStatus.APPROVED) { await tx.artwork.update({ where: { id }, @@ -893,7 +906,7 @@ export class ArtworkService { auditStatus: AuditStatus.REJECTED, auditRemark: dto.remark ?? null, auditedBy: auditorId, - auditedAt: new Date(), + auditedAt: reviewedAt, }, }); } diff --git a/apps/api/src/assets/templates/README.md b/apps/api/src/assets/templates/README.md index 0ff4422..ac7fb65 100644 --- a/apps/api/src/assets/templates/README.md +++ b/apps/api/src/assets/templates/README.md @@ -4,8 +4,11 @@ 模板必须与批量导入解析契约保持一致: -- ZIP 根目录必须且只能包含一个 `.xlsx` 文件;存在出库图时,图片放在 `images/` 目录。 +- ZIP 根目录必须且只能包含一个 `.xlsx` 文件;存在出库图时,按 `images/<追溯码>/文件名.jpg` 放置,目录内全部图片自动归属该追溯码。解析器只接受 `images/`,不兼容旧的 `image/` 目录。 - xlsx 第一张工作表是实际导入表,表头必须使用共享常量 `OUTBOUND_IMPORT_COLUMNS` 定义的列名。 - 实际导入表不要预置示例数据;示例可放在后续工作表。 +- 主表固定为“追溯码、批次编号、出库时间、备注”四列,不填写图片路径;已出库追溯码拒绝覆盖。 - 单个 xlsx、单张图片均不得超过 100MB;图片仅支持 JPG、JPEG、PNG、WebP,且不得超过 4000 万像素,不支持多帧图片。 +- 图片张数没有业务上限。ZIP 的 `100002` 个中央目录条目上限仅用于防止恶意目录耗尽内存,并不是图片业务上限;导入仍受磁盘空间、处理超时和其他安全检查约束。 +- 上传请求有 `Content-Length` 时会在落盘前按声明体积预检;分块上传没有该请求头时入口只能先检查最低 1GB 可用空间,上传完成后再按实际大小执行后续磁盘容量检查。 - 更新后运行 `pnpm --filter @artveris/api exec jest --runInBand src/outbound/outbound.service.spec.ts`,测试会校验 ZIP 结构、表头、说明和示例图片。 diff --git a/apps/api/src/assets/templates/outbound-import-template.zip b/apps/api/src/assets/templates/outbound-import-template.zip index 78d8d26..ec93e8e 100644 Binary files a/apps/api/src/assets/templates/outbound-import-template.zip and b/apps/api/src/assets/templates/outbound-import-template.zip differ diff --git a/apps/api/src/backup/backup.controller.ts b/apps/api/src/backup/backup.controller.ts index 2b92942..beee1b2 100644 --- a/apps/api/src/backup/backup.controller.ts +++ b/apps/api/src/backup/backup.controller.ts @@ -1,13 +1,29 @@ import { Body, Controller, Delete, Get, Param, Post, Query, Res, UploadedFile, UseInterceptors } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; import { ApiBearerAuth, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger'; +import { randomUUID } from 'crypto'; import { Response } from 'express'; -import { MAX_FILE_SIZE, RoleType } from '@artveris/shared'; +import { mkdirSync } from 'fs'; +import { rm } from 'fs/promises'; +import { tmpdir } from 'os'; +import { join, resolve } from 'path'; +import { diskStorage } from 'multer'; +import { RoleType } from '@artveris/shared'; import { Roles } from '../common/decorators/roles.decorator'; import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator'; import { BackupService } from './backup.service'; import { QueryBackupDto, RestoreCommitDto } from './dto/backup.dto'; +const BACKUP_UPLOAD_TEMP_DIR = resolve( + process.env.ARTVERIS_BACKUP_TEMP_DIR || join(tmpdir(), 'artveris-backup-uploads'), +); +mkdirSync(BACKUP_UPLOAD_TEMP_DIR, { recursive: true }); + +const backupDiskStorage = diskStorage({ + destination: BACKUP_UPLOAD_TEMP_DIR, + filename: (_req, _file, callback) => callback(null, `${randomUUID()}.upload`), +}); + @ApiTags('备份与恢复') @ApiBearerAuth() @Roles(RoleType.SUPER_ADMIN) @@ -42,9 +58,13 @@ export class BackupController { @Post('restore/preview') @ApiOperation({ summary: '上传备份包并预校验' }) @ApiConsumes('multipart/form-data') - @UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE * 10 } })) - restorePreview(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) { - return this.backups.previewRestore(file, user); + @UseInterceptors(FileInterceptor('file', { storage: backupDiskStorage, limits: { files: 1 } })) + async restorePreview(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) { + try { + return await this.backups.previewRestore(file, user); + } finally { + if (file?.path) await rm(file.path, { force: true }).catch(() => undefined); + } } @Post('restore/commit') diff --git a/apps/api/src/backup/backup.service.spec.ts b/apps/api/src/backup/backup.service.spec.ts index d01d371..7f33e30 100644 --- a/apps/api/src/backup/backup.service.spec.ts +++ b/apps/api/src/backup/backup.service.spec.ts @@ -1,89 +1,273 @@ -import { backfillOutboundImportJobIds } from './backup.service'; +import AdmZip from 'adm-zip'; +import { existsSync } from 'fs'; +import { copyFile, mkdtemp, readFile, readdir, rm, writeFile } from 'fs/promises'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import { + BackupService, + assertRestoreDiskCapacity, + validateBackupArchiveFile, + validateTraceCodeSequencePayload, +} from './backup.service'; +import { BackupController } from './backup.controller'; -describe('backfillOutboundImportJobIds', () => { - it('links legacy jobs and safely terminates an in-flight restored import', () => { - const db: Record = { - job: [ - { id: 'preview-old', type: 'IMPORT_OUTBOUND_PREVIEW', payload: { sessionId: 's1' }, createdAt: '2026-01-01' }, - { id: 'preview-new', type: 'IMPORT_OUTBOUND_PREVIEW', payload: { sessionId: 's1' }, createdAt: '2026-01-02' }, - { id: 'import-1', type: 'IMPORT_OUTBOUND', payload: { sessionId: 's1' }, createdAt: '2026-01-03' }, - ], - outboundImportSession: [{ id: 's1', status: 'IMPORTING' }], - }; +const MODEL_NAMES = [ + 'sysUser', + 'template', + 'templateField', + 'artwork', + 'artworkRevision', + 'traceNode', + 'certificate', + 'traceCodeGroup', + 'batch', + 'traceCode', + 'traceCodeSequence', + 'job', + 'onchainChunk', + 'blockchainProof', + 'jobItem', + 'outboundRecord', + 'outboundImage', + 'queryLog', + 'operationLog', + 'outboundImportSession', + 'outboundImportRow', + 'systemSetting', +] as const; - backfillOutboundImportJobIds(db); +function validDatabase(): Record { + const db = Object.fromEntries(MODEL_NAMES.map((model) => [model, []])) as Record; + db.traceCodeSequence = [{ id: 1, nextSeq: 2 }]; + db.traceCode = [{ serialNo: 1 }]; + return db; +} - expect((db.outboundImportSession as any[])[0]).toMatchObject({ - previewJobId: 'preview-new', - importJobId: 'import-1', - importRunToken: null, - status: 'FAILED', - error: '恢复备份时已安全终止进行中的导入任务,请重新上传', - }); +function backupManifest(files: string[]) { + const db = validDatabase(); + return { + app: 'artveris', + version: '2.0.0', + createdAt: new Date().toISOString(), + mode: 'BACKUP', + models: Object.fromEntries(Object.entries(db).map(([key, rows]) => [key, rows.length])), + files, + }; +} + +async function writeTestBackup( + filePath: string, + declaredFiles: string[], + storageFiles: Record = {}, +): Promise { + const zip = new AdmZip(); + zip.addFile('manifest.json', Buffer.from(JSON.stringify(backupManifest(declaredFiles)), 'utf8')); + zip.addFile('database.json', Buffer.from(JSON.stringify(validDatabase()), 'utf8')); + for (const [key, value] of Object.entries(storageFiles)) zip.addFile(`storage/${key}`, value); + await writeFile(filePath, zip.toBuffer()); +} + +function createService(root: string, overrides: { prisma?: any; storage?: any } = {}) { + const prisma = overrides.prisma || { + backupRecord: { + create: jest.fn().mockResolvedValue({ id: 'backup-1' }), + update: jest.fn(({ data }) => Promise.resolve({ id: 'backup-1', ...data })), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + findUnique: jest.fn(), + delete: jest.fn(), + }, + $transaction: jest.fn(), + }; + const storage = overrides.storage || { + listKeys: jest.fn().mockResolvedValue([]), + downloadToFile: jest.fn(), + putKeyFile: jest.fn(), + remove: jest.fn(), + }; + const config = { get: jest.fn((key: string) => key === 'storage.localDir' ? join(root, 'storage') : undefined) }; + const settings = { getAllRaw: jest.fn().mockResolvedValue({}) }; + const previousBackupDir = process.env.BACKUP_DIR; + process.env.BACKUP_DIR = join(root, 'backups'); + const service = new BackupService(prisma as any, config as any, settings as any, storage as any); + if (previousBackupDir === undefined) delete process.env.BACKUP_DIR; + else process.env.BACKUP_DIR = previousBackupDir; + return { service, prisma, storage }; +} + +describe('validateTraceCodeSequencePayload', () => { + it('accepts a sequence strictly above every restored serial number', () => { + expect(() => validateTraceCodeSequencePayload({ + traceCodeSequence: [{ id: 1, nextSeq: 102 }], + traceCode: [{ serialNo: 1 }, { serialNo: 101 }], + })).not.toThrow(); }); - it('terminates a legacy active session when its job is absent', () => { - const db: Record = { - job: [], - outboundImportSession: [{ id: 's1', status: 'PARSING', error: null }], - }; - - backfillOutboundImportJobIds(db); - - expect((db.outboundImportSession as any[])[0]).toMatchObject({ - status: 'FAILED', - error: '恢复备份时已安全终止进行中的导入任务,请重新上传', - }); + it('rejects a sequence that could reissue an existing serial number', () => { + expect(() => validateTraceCodeSequencePayload({ + traceCodeSequence: [{ id: 1, nextSeq: 101 }], + traceCode: [{ serialNo: 101 }], + })).toThrow('备份包追溯码流水无效'); }); - it('does not attach an abandoned failed import job to a READY session', () => { - const db: Record = { - job: [{ - id: 'abandoned-import', - type: 'IMPORT_OUTBOUND', - status: 'FAILED', - payload: { sessionId: 's1' }, - createdAt: '2026-01-03', - }], - outboundImportSession: [{ id: 's1', status: 'READY', importJobId: null }], + it('rejects missing, duplicate, or exhausted singleton sequence rows', () => { + expect(() => validateTraceCodeSequencePayload({ traceCodeSequence: [], traceCode: [] })) + .toThrow('备份包缺少有效的全局追溯码流水'); + expect(() => validateTraceCodeSequencePayload({ + traceCodeSequence: [{ id: 1, nextSeq: 1 }, { id: 2, nextSeq: 1 }], + traceCode: [], + })).toThrow('备份包缺少有效的全局追溯码流水'); + expect(() => validateTraceCodeSequencePayload({ + traceCodeSequence: [{ id: 1, nextSeq: 1_000_001 }], + traceCode: [], + })).toThrow('备份包追溯码流水无效'); + }); +}); + +describe('backup archive streaming and integrity', () => { + const roots: string[] = []; + + afterEach(async () => { + for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }); + jest.restoreAllMocks(); + }); + + async function tempRoot(): Promise { + const root = await mkdtemp(join(tmpdir(), 'artveris-backup-test-')); + roots.push(root); + return root; + } + + it('creates the ZIP from staged files without reading storage objects into buffers', async () => { + const root = await tempRoot(); + const source = join(root, 'source.bin'); + await writeFile(source, Buffer.alloc(4 * 1024 * 1024, 0x5a)); + const storage = { + listKeys: jest.fn().mockResolvedValue(['archive/source.bin']), + downloadToFile: jest.fn((_key: string, target: string) => copyFile(source, target)), + read: jest.fn(() => Promise.reject(new Error('buffer read must not be used'))), + }; + const { service, prisma } = createService(root, { storage }); + jest.spyOn(service as any, 'assertModelCoverage').mockImplementation(() => undefined); + jest.spyOn(service as any, 'dumpDatabase').mockResolvedValue(validDatabase()); + + await service.createBackup({ id: 1 } as any); + + expect(storage.downloadToFile).toHaveBeenCalledWith('archive/source.bin', expect.any(String)); + expect(storage.read).not.toHaveBeenCalled(); + const filePath = prisma.backupRecord.create.mock.calls[0][0].data.filePath; + await expect(validateBackupArchiveFile(filePath)).resolves.toMatchObject({ + storageFiles: [{ key: 'archive/source.bin', size: 4 * 1024 * 1024 }], + }); + expect((await readdir(join(root, 'backups'))).some((name) => name.startsWith('.backup-create-'))).toBe(false); + }); + + it('rejects missing and unlisted storage entries declared by manifest.files', async () => { + const root = await tempRoot(); + const missingPath = join(root, 'missing.zip'); + const unexpectedPath = join(root, 'unexpected.zip'); + await writeTestBackup(missingPath, ['missing.jpg']); + await writeTestBackup(unexpectedPath, [], { 'unexpected.jpg': Buffer.from('image') }); + + await expect(validateBackupArchiveFile(missingPath)).rejects.toThrow('备份包媒体清单不一致'); + await expect(validateBackupArchiveFile(unexpectedPath)).rejects.toThrow('备份包媒体清单不一致'); + }); + + it('rejects an entry whose data no longer matches the ZIP CRC', async () => { + const root = await tempRoot(); + const filePath = join(root, 'tampered.zip'); + await writeTestBackup(filePath, ['image.bin'], { 'image.bin': Buffer.alloc(1024, 0x41) }); + const archive = await readFile(filePath); + const entryName = Buffer.from('storage/image.bin'); + const nameOffset = archive.indexOf(entryName); + const localHeaderOffset = nameOffset - 30; + const extraLength = archive.readUInt16LE(localHeaderOffset + 28); + const dataOffset = nameOffset + entryName.length + extraLength; + archive[dataOffset] ^= 0xff; + await writeFile(filePath, archive); + + await expect(validateBackupArchiveFile(filePath)).rejects.toThrow(); + }); + + it('rejects restore staging when declared content exceeds available disk space', () => { + expect(() => assertRestoreDiskCapacity(4097n, 4096n)).toThrow('恢复临时磁盘空间不足'); + expect(() => assertRestoreDiskCapacity(4096n, 4096n)).not.toThrow(); + }); + + it('fails commit validation before snapshot, database deletion, or storage removal', async () => { + const root = await tempRoot(); + const filePath = join(root, 'invalid-restore.zip'); + await writeTestBackup(filePath, ['missing.jpg']); + const prisma = { + backupRecord: { + findUnique: jest.fn().mockResolvedValue({ id: 'restore-1', mode: 'RESTORE', filePath }), + update: jest.fn().mockResolvedValue({}), + updateMany: jest.fn().mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 1 }), + }, + $transaction: jest.fn(), }; + const storage = { listKeys: jest.fn(), remove: jest.fn(), putKeyFile: jest.fn() }; + const { service } = createService(root, { prisma, storage }); + const snapshot = jest.spyOn(service, 'createBackup').mockRejectedValue(new Error('must not run')); - backfillOutboundImportJobIds(db); - - expect((db.outboundImportSession as any[])[0].importJobId).toBeFalsy(); - }); - - it('normalizes legacy terminal import counts and partial status from restored rows', () => { - const db: Record = { - job: [{ - id: 'import-1', - type: 'IMPORT_OUTBOUND', - status: 'FAILED', - successCount: 0, - failCount: 0, - payload: { sessionId: 's1' }, - createdAt: '2026-01-03', - }], - outboundImportSession: [{ - id: 's1', - status: 'FAILED', - validCount: 3, - invalidCount: 0, - }], - outboundImportRow: [ - { sessionId: 's1', status: 'IMPORTED' }, - { sessionId: 's1', status: 'FAILED' }, - { sessionId: 's1', status: 'FAILED' }, - ], + await expect(service.commitRestore('restore-1', { id: 1 } as any)).rejects.toThrow('媒体清单不一致'); + + expect(snapshot).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + expect(storage.listKeys).not.toHaveBeenCalled(); + expect(storage.remove).not.toHaveBeenCalled(); + expect((await readdir(join(root, 'backups'))).some((name) => name.startsWith('.backup-restore-'))).toBe(false); + }); + + it('allows only one caller to claim a restore record and does not overwrite its status', async () => { + const root = await tempRoot(); + const filePath = join(root, 'restore.zip'); + await writeTestBackup(filePath, []); + const prisma = { + backupRecord: { + findUnique: jest.fn().mockResolvedValue({ id: 'restore-1', mode: 'RESTORE', filePath }), + update: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 0 }), + }, + $transaction: jest.fn(), }; + const { service, storage } = createService(root, { prisma }); + const snapshot = jest.spyOn(service, 'createBackup'); + + await expect(service.commitRestore('restore-1', { id: 1 } as any)).rejects.toMatchObject({ httpStatus: 409 }); - backfillOutboundImportJobIds(db); + expect(snapshot).not.toHaveBeenCalled(); + expect(prisma.backupRecord.updateMany).toHaveBeenCalledTimes(1); + expect(prisma.backupRecord.update).not.toHaveBeenCalled(); + expect(prisma.$transaction).not.toHaveBeenCalled(); + expect(storage.remove).not.toHaveBeenCalled(); + }); + + it('previews from a disk path without touching Multer file.buffer', async () => { + const root = await tempRoot(); + const uploadPath = join(root, 'upload.zip'); + await writeTestBackup(uploadPath, []); + const { service, prisma } = createService(root); + const file = { path: uploadPath } as Express.Multer.File; + Object.defineProperty(file, 'buffer', { get: () => { throw new Error('buffer must not be read'); } }); + + await expect(service.previewRestore(file, { id: 1 } as any)).resolves.toMatchObject({ restoreId: 'backup-1' }); + + const storedPath = prisma.backupRecord.create.mock.calls[0][0].data.filePath; + expect(existsSync(storedPath)).toBe(true); + }); + + it('removes the Multer disk upload after preview fails', async () => { + const root = await tempRoot(); + const uploadPath = join(root, 'invalid.upload'); + await writeFile(uploadPath, Buffer.from('not-a-zip')); + const backups = { previewRestore: jest.fn().mockRejectedValue(new Error('invalid backup')) }; + const controller = new BackupController(backups as any); - expect((db.outboundImportSession as any[])[0]).toMatchObject({ - importJobId: 'import-1', - status: 'PARTIAL', - validCount: 1, - invalidCount: 2, - }); + await expect(controller.restorePreview( + { path: uploadPath } as Express.Multer.File, + { id: 1 } as any, + )).rejects.toThrow('invalid backup'); + + expect(existsSync(uploadPath)).toBe(false); }); }); diff --git a/apps/api/src/backup/backup.service.ts b/apps/api/src/backup/backup.service.ts index 9c485b0..1f2827b 100644 --- a/apps/api/src/backup/backup.service.ts +++ b/apps/api/src/backup/backup.service.ts @@ -1,10 +1,12 @@ import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Response } from 'express'; -import AdmZip from 'adm-zip'; +import { randomUUID } from 'crypto'; import dayjs from 'dayjs'; -import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'; +import { createReadStream, createWriteStream, existsSync, mkdirSync } from 'fs'; +import { copyFile, mkdir, mkdtemp, open, readdir, rename, rm, stat, statfs, writeFile } from 'fs/promises'; import { dirname, isAbsolute, join, relative, resolve } from 'path'; +import { pipeline } from 'stream/promises'; import { Prisma } from '@prisma/client'; import { BackupStatus, ErrorCode } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; @@ -16,6 +18,9 @@ import { QueryBackupDto } from './dto/backup.dto'; import { SettingsService } from '../settings/settings.service'; import { StorageService } from '../storage/storage.service'; +const archiver: any = require('archiver'); +const unzipper: any = require('unzipper'); + const MODELS = [ 'sysUser', 'template', @@ -27,14 +32,18 @@ const MODELS = [ 'traceCodeGroup', 'batch', 'traceCode', - 'traceCodeDailySequence', - 'blockchainProof', - 'queryLog', + 'traceCodeSequence', 'job', - 'systemSetting', + 'onchainChunk', + 'blockchainProof', + 'jobItem', + 'outboundRecord', + 'outboundImage', + 'queryLog', 'operationLog', 'outboundImportSession', 'outboundImportRow', + 'systemSetting', ] as const; const DELETE_ORDER = [...MODELS].reverse(); @@ -50,14 +59,18 @@ const PRISMA_MODEL_BY_DELEGATE: Record<(typeof MODELS)[number], string> = { traceCodeGroup: 'TraceCodeGroup', batch: 'Batch', traceCode: 'TraceCode', - traceCodeDailySequence: 'TraceCodeDailySequence', - blockchainProof: 'BlockchainProof', - queryLog: 'QueryLog', + traceCodeSequence: 'TraceCodeSequence', job: 'Job', - systemSetting: 'SystemSetting', + onchainChunk: 'OnchainChunk', + blockchainProof: 'BlockchainProof', + jobItem: 'JobItem', + outboundRecord: 'OutboundRecord', + outboundImage: 'OutboundImage', + queryLog: 'QueryLog', operationLog: 'OperationLog', outboundImportSession: 'OutboundImportSession', outboundImportRow: 'OutboundImportRow', + systemSetting: 'SystemSetting', }; const DATE_KEYS = new Set([ 'lastLoginAt', @@ -73,6 +86,9 @@ const DATE_KEYS = new Set([ 'firstActivatedAt', 'lastQueriedAt', 'onchainAt', + 'lastSyncedAt', + 'unknownAt', + 'confirmedAt', 'queriedAt', 'expiresAt', 'committedAt', @@ -97,94 +113,60 @@ function reviveRow(row: Record): Record { return out; } -export function backfillOutboundImportJobIds(db: Record): void { - const jobs = Array.isArray(db.job) ? [...db.job] as Record[] : []; - const rows = Array.isArray(db.outboundImportRow) ? db.outboundImportRow as Record[] : []; - const sessions = Array.isArray(db.outboundImportSession) - ? db.outboundImportSession as Record[] - : []; - const links = new Map(); - jobs - .sort((a, b) => String(a.createdAt || '').localeCompare(String(b.createdAt || ''))) - .forEach((job) => { - const sessionId = job.payload && typeof job.payload === 'object' && !Array.isArray(job.payload) - ? String(job.payload.sessionId || '') - : ''; - if (!sessionId || typeof job.id !== 'string') return; - const link = links.get(sessionId) || {}; - if (job.type === 'IMPORT_OUTBOUND_PREVIEW') link.previewJobId = job.id; - if (job.type === 'IMPORT_OUTBOUND') link.importJobId = job.id; - links.set(sessionId, link); - }); - - for (const session of sessions) { - const restoredActiveStatus = String(session.status || ''); - const link = links.get(String(session.id || '')); - if (!session.previewJobId && link?.previewJobId) session.previewJobId = link.previewJobId; - if ( - !session.importJobId - && link?.importJobId - && ['IMPORTING', 'IMPORTED', 'PARTIAL', 'FAILED'].includes(String(session.status || '')) - ) { - session.importJobId = link.importJobId; - } - session.importRunToken = null; - - if (restoredActiveStatus === 'PARSING' || restoredActiveStatus === 'IMPORTING') { - const reason = '恢复备份时已安全终止进行中的导入任务,请重新上传'; - const sessionRows = rows.filter((row) => String(row.sessionId || '') === String(session.id || '')); - if (restoredActiveStatus === 'IMPORTING') { - sessionRows.forEach((row) => { - if (row.status === 'VALID') { - row.status = 'FAILED'; - row.reason = reason; - } - }); - const successCount = sessionRows.filter((row) => row.status === 'IMPORTED').length; - const failCount = sessionRows.filter((row) => row.status === 'FAILED').length; - session.validCount = successCount; - session.invalidCount = failCount; - session.status = successCount > 0 ? 'PARTIAL' : 'FAILED'; - const importJob = jobs.find((job) => job.id === session.importJobId); - if (importJob) { - importJob.status = successCount > 0 ? 'PARTIAL' : 'FAILED'; - importJob.successCount = successCount; - importJob.failCount = failCount; - importJob.error = reason; - importJob.resultFileUrl = `/outbound/import-sessions/${session.id}/result`; - } - } else { - session.status = 'FAILED'; - const previewJob = jobs.find((job) => job.id === session.previewJobId); - if (previewJob) { - previewJob.status = 'FAILED'; - previewJob.error = reason; - } - } - session.error = reason; - continue; - } - - const importJob = session.importJobId - ? jobs.find((job) => job.id === session.importJobId && job.type === 'IMPORT_OUTBOUND') - : undefined; - if (importJob && ['SUCCESS', 'PARTIAL', 'FAILED'].includes(String(importJob.status || ''))) { - const sessionRows = rows.filter((row) => String(row.sessionId || '') === String(session.id || '')); - const importedRows = sessionRows.filter((row) => row.status === 'IMPORTED').length; - const failedRows = sessionRows.filter((row) => row.status === 'FAILED').length; - const successCount = importedRows || Number(importJob.successCount || 0); - const failCount = failedRows || Number(importJob.failCount || 0); - session.validCount = successCount; - session.invalidCount = failCount; - session.status = successCount > 0 ? (failCount > 0 ? 'PARTIAL' : 'IMPORTED') : 'FAILED'; - } +export function validateTraceCodeSequencePayload(db: Record): void { + const sequences = Array.isArray(db.traceCodeSequence) ? db.traceCodeSequence as Record[] : []; + const traceCodes = Array.isArray(db.traceCode) ? db.traceCode as Record[] : []; + if (sequences.length !== 1 || Number(sequences[0]?.id) !== 1) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包缺少有效的全局追溯码流水'); + } + const nextSeq = Number(sequences[0].nextSeq); + const maxSerialNo = traceCodes.reduce((max, row) => Math.max(max, Number(row.serialNo) || 0), 0); + if (!Number.isInteger(nextSeq) || nextSeq < 1 || nextSeq > 1_000_000 || nextSeq <= maxSerialNo) { + throw new BusinessException( + ErrorCode.BAD_REQUEST, + `备份包追溯码流水无效:nextSeq=${nextSeq},maxSerialNo=${maxSerialNo}`, + ); } } -const BACKUP_FORMAT_VERSION = '0.1.0'; +const BACKUP_FORMAT_VERSION = '2.0.0'; + +interface BackupArchiveEntry { + path: string; + type: 'File' | 'Directory'; + crc32: number; + uncompressedSize: number; + stream: () => NodeJS.ReadableStream; +} + +interface ValidatedBackupArchive { + manifest: Record; + db: Record; + storageFiles: Array<{ key: string; size: number }>; +} + +const CRC32_TABLE = new Uint32Array(256); +for (let index = 0; index < CRC32_TABLE.length; index += 1) { + let value = index; + for (let bit = 0; bit < 8; bit += 1) { + value = (value & 1) ? (0xedb88320 ^ (value >>> 1)) : (value >>> 1); + } + CRC32_TABLE[index] = value >>> 0; +} + +function updateCrc32(crc: number, data: Buffer): number { + let next = crc; + for (const byte of data) next = CRC32_TABLE[(next ^ byte) & 0xff] ^ (next >>> 8); + return next >>> 0; +} function isSafeZipPath(path: string): boolean { - return !path.includes('\\') && !path.includes('..') && !path.startsWith('/') && !/^[a-z]:/i.test(path); + return Boolean(path) + && !path.includes('\\') + && !path.includes('..') + && !path.startsWith('/') + && !/^[a-z]:/i.test(path) + && !/[\x00-\x1f]/.test(path); } // 恢复前的强校验:确认是 Artveris 备份、版本主号兼容、且 database.json 覆盖全部业务表, @@ -211,6 +193,7 @@ function validateBackupPayload(manifest: any, db: unknown): void { `备份包缺少数据表:${missing.join(', ')};已中止恢复以避免清空现有数据`, ); } + validateTraceCodeSequencePayload(data); } function isSameOrChildPath(parent: string, child: string): boolean { @@ -218,6 +201,178 @@ function isSameOrChildPath(parent: string, child: string): boolean { return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel)); } +function archiveListSummary(values: string[]): string { + const shown = values.slice(0, 10).join(', '); + return values.length > 10 ? `${shown} 等 ${values.length} 项` : shown; +} + +export function assertRestoreDiskCapacity(requiredBytes: bigint, availableBytes: bigint): void { + if (requiredBytes > availableBytes) { + throw new BusinessException( + ErrorCode.BAD_REQUEST, + `恢复临时磁盘空间不足:需要 ${requiredBytes} 字节,可用 ${availableBytes} 字节`, + ); + } +} + +async function readVerifiedArchiveEntry(entry: BackupArchiveEntry, targetPath?: string): Promise { + const declaredSize = Number(entry.uncompressedSize); + if (!Number.isSafeInteger(declaredSize) || declaredSize < 0) { + throw new BusinessException(ErrorCode.BAD_REQUEST, `备份包文件大小无效:${entry.path}`); + } + + const chunks: Buffer[] | undefined = targetPath ? undefined : []; + const target = targetPath ? await open(targetPath, 'wx') : undefined; + let total = 0; + let crc = 0xffffffff; + try { + for await (const chunk of entry.stream()) { + const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + total += data.length; + if (total > declaredSize) { + throw new BusinessException(ErrorCode.BAD_REQUEST, `备份包文件实际大小超过声明:${entry.path}`); + } + crc = updateCrc32(crc, data); + if (target) { + let offset = 0; + while (offset < data.length) { + const result = await target.write(data, offset, data.length - offset); + if (!result.bytesWritten) throw new Error(`写入恢复临时文件失败:${entry.path}`); + offset += result.bytesWritten; + } + } else { + chunks!.push(data); + } + } + } catch (error) { + await target?.close().catch(() => undefined); + if (targetPath) await rm(targetPath, { force: true }).catch(() => undefined); + throw error; + } + await target?.close(); + + const actualCrc = (~crc) >>> 0; + const declaredCrc = Number(entry.crc32) >>> 0; + if (total !== declaredSize || actualCrc !== declaredCrc) { + if (targetPath) await rm(targetPath, { force: true }).catch(() => undefined); + throw new BusinessException(ErrorCode.BAD_REQUEST, `备份包文件校验失败:${entry.path}`); + } + return chunks ? Buffer.concat(chunks, total) : undefined; +} + +export async function validateBackupArchiveFile( + filePath: string, + storageTargetRoot?: string, +): Promise { + let directory: { files: BackupArchiveEntry[] }; + try { + directory = await unzipper.Open.file(filePath); + } catch { + throw new BusinessException(ErrorCode.BAD_REQUEST, '备份 ZIP 文件结构无效'); + } + + const entries = Array.isArray(directory.files) ? directory.files : []; + if (storageTargetRoot) { + await mkdir(storageTargetRoot, { recursive: true }); + let requiredBytes = 0n; + for (const entry of entries) { + if (entry.type === 'Directory') continue; + const size = Number(entry.uncompressedSize); + if (!Number.isSafeInteger(size) || size < 0) { + throw new BusinessException(ErrorCode.BAD_REQUEST, `备份包文件大小无效:${entry.path}`); + } + requiredBytes += BigInt(size); + } + const disk = await statfs(storageTargetRoot); + const availableBytes = BigInt(disk.bavail) * BigInt(disk.bsize); + assertRestoreDiskCapacity(requiredBytes, availableBytes); + } + const byPath = new Map(); + const storageEntries = new Map(); + for (const entry of entries) { + const entryPath = String(entry.path || ''); + if (!isSafeZipPath(entryPath)) { + throw new BusinessException(ErrorCode.BAD_REQUEST, `备份包包含不安全文件路径:${entryPath || '(空路径)'}`); + } + if (byPath.has(entryPath)) { + throw new BusinessException(ErrorCode.BAD_REQUEST, `备份包包含重复文件条目:${entryPath}`); + } + byPath.set(entryPath, entry); + if (entry.type === 'Directory') { + if (entryPath !== 'storage/' && !entryPath.startsWith('storage/')) { + throw new BusinessException(ErrorCode.BAD_REQUEST, `备份包包含未知目录:${entryPath}`); + } + continue; + } + if (entryPath === 'manifest.json' || entryPath === 'database.json') continue; + if (!entryPath.startsWith('storage/')) { + throw new BusinessException(ErrorCode.BAD_REQUEST, `备份包包含未知文件:${entryPath}`); + } + const key = entryPath.slice('storage/'.length); + if (!isSafeZipPath(key)) { + throw new BusinessException(ErrorCode.BAD_REQUEST, `备份包包含不安全文件路径:${entryPath}`); + } + storageEntries.set(key, entry); + } + + const manifestEntry = byPath.get('manifest.json'); + const databaseEntry = byPath.get('database.json'); + if (!manifestEntry || manifestEntry.type !== 'File' || !databaseEntry || databaseEntry.type !== 'File') { + throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包缺少 manifest.json 或 database.json'); + } + + let manifest: Record; + let db: Record; + try { + const manifestBuffer = await readVerifiedArchiveEntry(manifestEntry); + const databaseBuffer = await readVerifiedArchiveEntry(databaseEntry); + manifest = JSON.parse(manifestBuffer!.toString('utf8')); + db = JSON.parse(databaseBuffer!.toString('utf8')); + } catch (error) { + if (error instanceof BusinessException) throw error; + throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包 manifest.json 或 database.json 无效'); + } + validateBackupPayload(manifest, db); + + if (!Array.isArray(manifest.files)) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包 manifest.files 结构无效'); + } + const declaredFiles: string[] = []; + const declaredSet = new Set(); + for (const value of manifest.files) { + if (typeof value !== 'string' || !isSafeZipPath(value) || declaredSet.has(value)) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包 manifest.files 包含无效或重复路径'); + } + declaredSet.add(value); + declaredFiles.push(value); + } + + const missing = declaredFiles.filter((key) => !storageEntries.has(key)); + const unexpected = [...storageEntries.keys()].filter((key) => !declaredSet.has(key)); + if (missing.length || unexpected.length) { + const details = [ + missing.length ? `缺失:${archiveListSummary(missing)}` : '', + unexpected.length ? `未声明:${archiveListSummary(unexpected)}` : '', + ].filter(Boolean).join(';'); + throw new BusinessException(ErrorCode.BAD_REQUEST, `备份包媒体清单不一致(${details})`); + } + + const storageFiles: Array<{ key: string; size: number }> = []; + for (const key of declaredFiles) { + const entry = storageEntries.get(key)!; + const targetPath = storageTargetRoot ? resolve(storageTargetRoot, key) : undefined; + if (targetPath) { + if (!isSameOrChildPath(storageTargetRoot!, targetPath) || targetPath === resolve(storageTargetRoot!)) { + throw new BusinessException(ErrorCode.BAD_REQUEST, `备份包包含不安全文件路径:storage/${key}`); + } + await mkdir(dirname(targetPath), { recursive: true }); + } + await readVerifiedArchiveEntry(entry, targetPath); + storageFiles.push({ key, size: Number(entry.uncompressedSize) }); + } + return { manifest, db, storageFiles }; +} + @Injectable() export class BackupService { private readonly storageRoot: string; @@ -249,37 +404,47 @@ export class BackupService { async createBackup(user: AuthUser, mode = 'BACKUP') { this.assertModelCoverage(); const stamp = dayjs().format('YYYYMMDDHHmmss'); - const fileName = `artveris-${mode.toLowerCase()}-${stamp}.zip`; + const fileName = `artveris-${mode.toLowerCase()}-${stamp}-${randomUUID()}.zip`; const filePath = join(this.backupRoot, fileName); const record = await this.prisma.backupRecord.create({ data: { fileName, filePath, status: BackupStatus.PROCESSING, mode, createdBy: user.id }, }); + let workingRoot: string | undefined; try { + workingRoot = await mkdtemp(join(this.backupRoot, '.backup-create-')); const db = await this.dumpDatabase(); - const zip = new AdmZip(); - const fileList = await this.addStorageFiles(zip); + const fileList = await this.stageStorageFiles(join(workingRoot, 'storage')); const manifest = { app: 'artveris', - version: '0.1.0', + version: BACKUP_FORMAT_VERSION, createdAt: new Date().toISOString(), mode, models: Object.fromEntries(Object.entries(db).map(([key, rows]) => [key, (rows as unknown[]).length])), files: fileList, }; - zip.addFile('manifest.json', Buffer.from(JSON.stringify(manifest, null, 2), 'utf8')); - zip.addFile('database.json', Buffer.from(JSON.stringify(db, jsonReplacer), 'utf8')); - writeFileSync(filePath, zip.toBuffer()); - const size = BigInt(statSync(filePath).size); + const manifestPath = join(workingRoot, 'manifest.json'); + const databasePath = join(workingRoot, 'database.json'); + const archivePath = join(workingRoot, 'backup.zip'); + await Promise.all([ + writeFile(manifestPath, JSON.stringify(manifest, null, 2), 'utf8'), + writeFile(databasePath, JSON.stringify(db, jsonReplacer), 'utf8'), + ]); + await this.writeBackupArchive(archivePath, workingRoot, fileList); + await rename(archivePath, filePath); + const size = BigInt((await stat(filePath)).size); return this.prisma.backupRecord.update({ where: { id: record.id }, data: { status: BackupStatus.SUCCESS, size, manifest: manifest as any }, }); } catch (e) { + await rm(filePath, { force: true }).catch(() => undefined); await this.prisma.backupRecord.update({ where: { id: record.id }, data: { status: BackupStatus.FAILED, error: (e as Error).message }, }); throw e; + } finally { + if (workingRoot) await rm(workingRoot, { recursive: true, force: true }).catch(() => undefined); } } @@ -290,42 +455,41 @@ export class BackupService { } res.setHeader('Content-Type', 'application/zip'); res.setHeader('Content-Disposition', `attachment; filename="${record.fileName}"`); - res.end(readFileSync(record.filePath)); + res.setHeader('Content-Length', String((await stat(record.filePath)).size)); + await pipeline(createReadStream(record.filePath), res); } async remove(id: string) { const record = await this.prisma.backupRecord.findUnique({ where: { id } }); if (!record) throw new BusinessException(ErrorCode.NOT_FOUND, '备份记录不存在', 404); - if (existsSync(record.filePath)) rmSync(record.filePath, { force: true }); + if (existsSync(record.filePath)) await rm(record.filePath, { force: true }); await this.prisma.backupRecord.delete({ where: { id } }); return { success: true }; } async previewRestore(file: Express.Multer.File, user: AuthUser) { - if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传备份 ZIP 文件'); - const zip = new AdmZip(file.buffer); - const manifestEntry = zip.getEntry('manifest.json'); - const dbEntry = zip.getEntry('database.json'); - if (!manifestEntry || !dbEntry) throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包缺少 manifest.json 或 database.json'); - const manifest = JSON.parse(manifestEntry.getData().toString('utf8')); - const db = JSON.parse(dbEntry.getData().toString('utf8')); - validateBackupPayload(manifest, db); - - const fileName = `restore-${dayjs().format('YYYYMMDDHHmmss')}.zip`; + if (!file?.path) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传备份 ZIP 文件'); + const fileName = `restore-${dayjs().format('YYYYMMDDHHmmss')}-${randomUUID()}.zip`; const filePath = join(this.backupRoot, fileName); - writeFileSync(filePath, file.buffer); - const record = await this.prisma.backupRecord.create({ - data: { - fileName, - filePath, - size: BigInt(file.buffer.length), - status: BackupStatus.PENDING, - mode: 'RESTORE', - manifest, - createdBy: user.id, - }, - }); - return { restoreId: record.id, manifest }; + try { + await copyFile(file.path, filePath); + const { manifest } = await validateBackupArchiveFile(filePath); + const record = await this.prisma.backupRecord.create({ + data: { + fileName, + filePath, + size: BigInt((await stat(filePath)).size), + status: BackupStatus.PENDING, + mode: 'RESTORE', + manifest, + createdBy: user.id, + }, + }); + return { restoreId: record.id, manifest }; + } catch (error) { + await rm(filePath, { force: true }).catch(() => undefined); + throw error; + } } async commitRestore(restoreId: string, user: AuthUser) { @@ -333,22 +497,40 @@ export class BackupService { if (!record || record.mode !== 'RESTORE' || !existsSync(record.filePath)) { throw new BusinessException(ErrorCode.NOT_FOUND, '恢复记录不存在', 404); } - await this.prisma.backupRecord.update({ where: { id: restoreId }, data: { status: BackupStatus.PROCESSING } }); - const snapshot = await this.createBackup(user, 'AUTO_BEFORE_RESTORE'); + const claim = await this.prisma.backupRecord.updateMany({ + where: { + id: restoreId, + mode: 'RESTORE', + status: { in: [BackupStatus.PENDING, BackupStatus.FAILED] }, + }, + data: { status: BackupStatus.PROCESSING, error: null }, + }); + if (claim.count !== 1) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '恢复任务正在处理或已经完成', 409); + } + let workingRoot: string | undefined; + let snapshot: { fileName: string } | undefined; try { - const zip = new AdmZip(readFileSync(record.filePath)); - await this.restoreDatabase(zip); - await this.restoreStorage(zip); + workingRoot = await mkdtemp(join(this.backupRoot, '.backup-restore-')); + const validated = await validateBackupArchiveFile(record.filePath, join(workingRoot, 'storage')); + snapshot = await this.createBackup(user, 'AUTO_BEFORE_RESTORE'); + await this.restoreDatabase(validated.manifest, validated.db); + await this.restoreStorage(validated.storageFiles, join(workingRoot, 'storage')); return this.prisma.backupRecord.update({ where: { id: restoreId }, data: { status: BackupStatus.SUCCESS, error: null }, }); } catch (e) { - await this.prisma.backupRecord.update({ - where: { id: restoreId }, - data: { status: BackupStatus.FAILED, error: `${(e as Error).message};恢复前快照:${snapshot.fileName}` }, + await this.prisma.backupRecord.updateMany({ + where: { id: restoreId, mode: 'RESTORE', status: BackupStatus.PROCESSING }, + data: { + status: BackupStatus.FAILED, + error: `${(e as Error).message}${snapshot ? `;恢复前快照:${snapshot.fileName}` : ''}`, + }, }); throw e; + } finally { + if (workingRoot) await rm(workingRoot, { recursive: true, force: true }).catch(() => undefined); } } @@ -384,45 +566,90 @@ export class BackupService { return [...byKey.values()]; } - private async addStorageFiles(zip: AdmZip) { + private stagePath(root: string, key: string): string { + const target = resolve(root, key); + if (!isSafeZipPath(key) || !isSameOrChildPath(root, target) || target === resolve(root)) { + throw new Error(`存储中包含不安全文件路径:${key}`); + } + return target; + } + + private async stageStorageFiles(targetRoot: string): Promise { const files: string[] = []; const storageKeys = await this.storage.listKeys(); if (storageKeys.length) { - for (const key of storageKeys) { - if (!isSafeZipPath(key)) continue; + const uniqueKeys = [...new Set(storageKeys)].sort(); + if (uniqueKeys.length !== storageKeys.length) throw new Error('存储驱动返回了重复文件 key'); + for (const key of uniqueKeys) { + const target = this.stagePath(targetRoot, key); + await mkdir(dirname(target), { recursive: true }); + await this.storage.downloadToFile(key, target); files.push(key); - zip.addFile(`storage/${key}`, await this.storage.read(key)); } return files; } if (!existsSync(this.storageRoot)) return files; - const walk = (dir: string) => { - for (const name of readdirSync(dir)) { - const full = join(dir, name); - const st = statSync(full); + const walk = async (dir: string): Promise => { + const entries = await readdir(dir, { withFileTypes: true }); + entries.sort((left, right) => left.name.localeCompare(right.name)); + for (const entry of entries) { + const full = join(dir, entry.name); if (isSameOrChildPath(this.backupRoot, full)) continue; - if (st.isDirectory()) { - walk(full); - } else { + if (entry.isDirectory()) { + await walk(full); + } else if (entry.isFile()) { const rel = relative(this.storageRoot, full).replace(/\\/g, '/'); - if (!isSafeZipPath(rel)) continue; + const target = this.stagePath(targetRoot, rel); + await mkdir(dirname(target), { recursive: true }); + await copyFile(full, target); files.push(rel); - zip.addFile(`storage/${rel}`, readFileSync(full)); } } }; - walk(this.storageRoot); + await walk(this.storageRoot); return files; } - private async restoreDatabase(zip: AdmZip) { - const entry = zip.getEntry('database.json'); - const manifestEntry = zip.getEntry('manifest.json'); - if (!entry || !manifestEntry) throw new Error('备份包缺少 database.json 或 manifest.json'); - const db = JSON.parse(entry.getData().toString('utf8')); - // 清库前再次校验,纵深防御,避免绕过 preview 直接 commit 的坏包清空数据 - validateBackupPayload(JSON.parse(manifestEntry.getData().toString('utf8')), db); - backfillOutboundImportJobIds(db); + private async writeBackupArchive(filePath: string, workingRoot: string, files: string[]): Promise { + const output = createWriteStream(filePath, { flags: 'wx' }); + const archive = archiver('zip', { forceZip64: true, zlib: { level: 6 } }); + await new Promise((resolvePromise, rejectPromise) => { + let settled = false; + const resolveOnce = () => { + if (!settled) { + settled = true; + resolvePromise(); + } + }; + const rejectOnce = (error: Error) => { + if (settled) return; + settled = true; + try { + archive.abort(); + } catch { + // 输出流关闭仍会释放文件句柄。 + } + output.destroy(); + if (output.closed) rejectPromise(error); + else output.once('close', () => rejectPromise(error)); + }; + output.once('close', resolveOnce); + output.once('error', rejectOnce); + archive.once('error', rejectOnce); + archive.once('warning', rejectOnce); + archive.pipe(output); + archive.file(join(workingRoot, 'manifest.json'), { name: 'manifest.json' }); + archive.file(join(workingRoot, 'database.json'), { name: 'database.json' }); + for (const key of files) { + archive.file(this.stagePath(join(workingRoot, 'storage'), key), { name: `storage/${key}` }); + } + Promise.resolve(archive.finalize()).catch(rejectOnce); + }); + } + + private async restoreDatabase(manifest: Record, db: Record) { + // 清库前再次校验,纵深防御,避免未来调用方绕过预检直接覆盖数据。 + validateBackupPayload(manifest, db); await this.prisma.$transaction(async (tx) => { for (const model of DELETE_ORDER) { await (tx as any)[model].deleteMany(); @@ -431,14 +658,6 @@ export class BackupService { const rows = Array.isArray(db[model]) ? db[model].map((row: unknown) => { const revived = reviveRow(row as Record) as Record; - // 兼容移除第二套完整编码前生成的历史备份。 - if (model === 'traceCode' || model === 'queryLog') delete revived.code; - // 兼容出库导入不再接收手工链上字段前生成的历史备份。 - if (model === 'outboundImportRow') { - delete revived.txHash; - delete revived.onchainAt; - delete revived.blockHeight; - } return revived; }) : []; @@ -447,25 +666,30 @@ export class BackupService { }, { timeout: 120000 }); } - private async restoreStorage(zip: AdmZip) { + private async restoreStorage(files: Array<{ key: string; size: number }>, stagedRoot: string) { + for (const file of files) { + const staged = this.stagePath(stagedRoot, file.key); + const stagedStat = await stat(staged); + if (!stagedStat.isFile() || stagedStat.size !== file.size) { + throw new Error(`恢复临时文件缺失或大小不一致:${file.key}`); + } + } + const currentKeys = await this.storage.listKeys(); if (currentKeys.length) { for (const key of currentKeys) { if (!key.startsWith('.health/')) await this.storage.remove(key); } } else { - mkdirSync(this.storageRoot, { recursive: true }); - for (const name of readdirSync(this.storageRoot)) { + await mkdir(this.storageRoot, { recursive: true }); + for (const name of await readdir(this.storageRoot)) { const full = join(this.storageRoot, name); if (isSameOrChildPath(this.backupRoot, full)) continue; - rmSync(full, { recursive: true, force: true }); + await rm(full, { recursive: true, force: true }); } } - for (const entry of zip.getEntries()) { - if (entry.isDirectory || !entry.entryName.startsWith('storage/')) continue; - const rel = entry.entryName.slice('storage/'.length); - if (!isSafeZipPath(rel)) throw new Error(`备份包包含不安全文件路径:${entry.entryName}`); - await this.storage.putKey(rel, entry.getData()); + for (const file of files) { + await this.storage.putKeyFile(file.key, this.stagePath(stagedRoot, file.key)); } } } diff --git a/apps/api/src/blockchain/attestation.service.ts b/apps/api/src/blockchain/attestation.service.ts index 119a107..3c49902 100644 --- a/apps/api/src/blockchain/attestation.service.ts +++ b/apps/api/src/blockchain/attestation.service.ts @@ -1,163 +1,228 @@ -import { Injectable } from '@nestjs/common'; import { InjectQueue } from '@nestjs/bullmq'; +import { Injectable, Logger } from '@nestjs/common'; +import { JobItemStatus, JobStatus, JobType, OnchainChunkStatus, Prisma, ProofStatus } from '@prisma/client'; import { Queue } from 'bullmq'; -import { ErrorCode, ProofStatus, QUEUE_NAMES } from '@artveris/shared'; -import { PrismaService } from '../prisma/prisma.service'; +import { ErrorCode, QUEUE_NAMES, RoleType } from '@artveris/shared'; +import { AuthUser } from '../common/decorators/current-user.decorator'; import { BusinessException } from '../common/exceptions/business.exception'; -import { StorageService } from '../storage/storage.service'; -import { isOutbound } from '../outbound/outbound.util'; +import { PrismaService } from '../prisma/prisma.service'; import { BlockchainService } from './blockchain.service'; +import { + CreateOnchainJobDto, + MarkOnchainFailedDto, + RecordOnchainTransactionDto, +} from './dto/onchain.dto'; +import { enqueueOnchain } from './onchain.queue'; +import { buildOnchainSelectionWhere } from './onchain.selection'; @Injectable() export class AttestationService { + private readonly logger = new Logger(AttestationService.name); + constructor( private readonly prisma: PrismaService, private readonly blockchain: BlockchainService, - private readonly storage: StorageService, @InjectQueue(QUEUE_NAMES.ONCHAIN) private readonly queue: Queue, ) {} - // 取作品主图的公开 URL 作为发行 feature(天河文档:feature=作品对应媒体文件地址;媒体本体存我方 OSS) - private firstImageUrl(images: unknown): string | undefined { - const list = Array.isArray(images) ? images : []; - const first = list[0] as { key?: string } | string | undefined; - const key = typeof first === 'string' ? first : first?.key; - return key ? this.storage.getUrl(key) : undefined; - } - - async trigger(traceCodeId: bigint) { - const code = await this.prisma.traceCode.findUnique({ - where: { id: traceCodeId }, - include: { - batch: true, - artwork: { include: { traceNodes: true, certificates: true } }, - }, - }); - if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404); - if (!code.artworkId || !code.artwork) { - throw new BusinessException(ErrorCode.BAD_REQUEST, '追溯码未绑定作品,无法上链'); + async createJob(dto: CreateOnchainJobDto, user: AuthUser) { + const { where, orderedIds } = buildOnchainSelectionWhere(dto.selection); + const snapshotMaxId = orderedIds + ? orderedIds.reduce((max, id) => (id > max ? id : max), 0n) + : (await this.prisma.traceCode.aggregate({ where, _max: { id: true } }))._max.id; + if (!snapshotMaxId) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '没有符合条件的追溯码'); } - // 上链代表已登记出库:未出库不允许上链(杜绝「已上链未登记」的不一致状态) - if (!isOutbound(code)) { - throw new BusinessException(ErrorCode.BAD_REQUEST, '该追溯码尚未登记出库,请先登记出库再上链'); - } - - // 防重复上链:已存在「上链成功/上链中/待上链」的存证则拒绝;仅失败(FAILED)的可再次发起。 - const active = await this.prisma.blockchainProof.findFirst({ - where: { - traceCodeId, - status: { in: [ProofStatus.ONCHAIN, ProofStatus.CONFIRMING, ProofStatus.PENDING] }, - }, - orderBy: { id: 'desc' }, - }); - if (active) { - const msg = - active.status === ProofStatus.ONCHAIN - ? '该追溯码已上链,不可重复上链' - : '该追溯码正在上链处理中,请稍候'; - throw new BusinessException(ErrorCode.BAD_REQUEST, msg); - } - - const summary = { - shortCode: code.shortCode, - title: code.artwork.title, - artist: code.artwork.artist, - archiveNo: code.artwork.archiveNo, - batchNo: code.batch.batchNo, - outbound: { - outTime: code.outTime, - outImages: code.outImages, - }, - dynamicFields: code.artwork.dynamicFields, - nodes: code.artwork.traceNodes.map((n) => ({ type: n.nodeType, title: n.title })), - certificates: code.artwork.certificates.map((c) => c.name), + const payload: Prisma.InputJsonObject = { + phase: 'SELECTING', + selection: JSON.parse(JSON.stringify(dto.selection)) as Prisma.InputJsonObject, + snapshotMaxId: snapshotMaxId.toString(), }; - const dataHash = this.blockchain.hashData(summary); - const proof = await this.prisma.blockchainProof.create({ + const job = await this.prisma.job.create({ data: { - traceCodeId, - dataHash, - status: ProofStatus.PENDING, - rawResponse: { - requestMeta: summary, - // 发行 NFT 用的产品信息(天河链:productId=追溯码、name=作品名、author=艺术家、feature=作品主图 OSS 地址) - product: { - productId: code.shortCode, - name: code.artwork.title, - author: code.artwork.artist ?? undefined, - feature: this.firstImageUrl(code.artwork.images), - }, - }, + type: JobType.ONCHAIN, + status: JobStatus.PENDING, + total: orderedIds?.length ?? 0, + createdBy: user.id, + payload, }, }); - // 入队失败(如 Redis 抖动)时把 proof 标记 FAILED,避免留下永远处理不了的 PENDING 悬挂记录 try { - await this.queue.add('onchain', { proofId: proof.id }); - } catch (e) { - await this.markQueueFailed(proof.id, proof.rawResponse, e); - throw new BusinessException(ErrorCode.INTERNAL_ERROR, '上链任务入队失败,请稍后重试'); + await enqueueOnchain(this.queue, { action: 'prepare', jobId: job.id }); + } catch (error) { + this.logger.warn(`上链任务等待恢复入队:job=${job.id} ${(error as Error).message}`); } - return proof; + return job; } - private async markQueueFailed(proofId: number, raw: unknown, e: unknown) { - await this.prisma.blockchainProof.update({ - where: { id: proofId }, - data: { - status: ProofStatus.FAILED, - rawResponse: { - ...(raw && typeof raw === 'object' ? (raw as object) : {}), - enqueueError: (e as Error).message, - failedAt: new Date().toISOString(), - }, - }, - }); + trigger(traceCodeId: bigint, user: AuthUser) { + return this.createJob({ selection: { mode: 'IDS', ids: [traceCodeId.toString()] } }, user); } - async retry(proofId: number) { + async retry(proofId: number, user: AuthUser) { const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } }); - if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '存证记录不存在', 404); - await this.prisma.blockchainProof.update({ - where: { id: proofId }, - data: { - status: ProofStatus.PENDING, - txHash: null, - blockHash: null, - blockHeight: null, - chainName: null, - explorerUrl: null, - onchainAt: null, - rawResponse: { - ...(proof.rawResponse && typeof proof.rawResponse === 'object' ? (proof.rawResponse as object) : {}), - retriedAt: new Date().toISOString(), - }, - }, - }); - try { - await this.queue.add('onchain', { proofId }); - } catch (e) { - await this.markQueueFailed(proofId, proof.rawResponse, e); - throw new BusinessException(ErrorCode.INTERNAL_ERROR, '上链任务入队失败,请稍后重试'); + if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '上链记录不存在', 404); + if (proof.status !== ProofStatus.FAILED) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '只有已明确失败的上链记录可以重新上链'); } - return { success: true }; + return this.trigger(proof.traceCodeId, user); } async confirm(proofId: number) { const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } }); - if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '存证记录不存在', 404); + if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '上链记录不存在', 404); if (proof.status === ProofStatus.ONCHAIN) return { success: true }; - if (!proof.txHash) throw new BusinessException(ErrorCode.BAD_REQUEST, '缺少交易哈希,无法重新确认'); - await this.prisma.blockchainProof.update({ - where: { id: proofId }, - data: { - status: ProofStatus.CONFIRMING, - rawResponse: { - ...(proof.rawResponse && typeof proof.rawResponse === 'object' ? (proof.rawResponse as object) : {}), - manualConfirmQueuedAt: new Date().toISOString(), - }, - }, - }); - await this.queue.add('confirm-onchain', { proofId, action: 'confirm', confirmAttempt: 1, manual: true }); + if (!proof.onchainChunkId) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '该上链记录缺少分片信息,无法安全同步'); + } + return this.resync(proof.onchainChunkId); + } + + async resync(chunkId: string) { + const chunk = await this.prisma.onchainChunk.findUnique({ where: { id: chunkId } }); + if (!chunk) throw new BusinessException(ErrorCode.NOT_FOUND, '上链分片不存在', 404); + if (chunk.status !== OnchainChunkStatus.UNKNOWN && chunk.status !== OnchainChunkStatus.CONFIRMING) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '只有待核实或确认中的分片可以安全同步'); + } + await enqueueOnchain( + this.queue, + chunk.status === OnchainChunkStatus.CONFIRMING + ? { action: 'confirm', chunkId } + : { action: 'resync', chunkId }, + ); return { success: true }; } + + async recordTransaction(proofId: number, dto: RecordOnchainTransactionDto) { + const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } }); + if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '上链记录不存在', 404); + if (proof.status !== ProofStatus.UNKNOWN || !proof.onchainChunkId) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '只有结果待核实的上链记录可以补录交易哈希'); + } + const chunkId = proof.onchainChunkId; + const explorerUrl = await this.blockchain.explorerTxUrl(dto.txHash.trim()); + const outcome = await this.prisma.$transaction(async (tx) => { + const changed = await tx.blockchainProof.updateMany({ + where: { id: proofId, status: ProofStatus.UNKNOWN }, + data: { + txHash: dto.txHash.trim(), + tokenId: dto.tokenId ? BigInt(dto.tokenId) : proof.tokenId, + explorerUrl, + status: ProofStatus.CONFIRMING, + lastSyncedAt: new Date(), + failureReason: null, + }, + }); + if (changed.count !== 1) throw new Error('上链记录状态已变化'); + await tx.jobItem.updateMany({ + where: { proofId, status: JobItemStatus.UNKNOWN }, + data: { status: JobItemStatus.PROCESSING, error: null }, + }); + const unresolvedWithoutTx = await tx.blockchainProof.count({ + where: { onchainChunkId: chunkId, status: ProofStatus.UNKNOWN, txHash: null }, + }); + if (unresolvedWithoutTx !== 0) return { unresolvedWithoutTx, confirmationStarted: false }; + const chunkChanged = await tx.onchainChunk.updateMany({ + where: { id: chunkId, status: OnchainChunkStatus.UNKNOWN }, + data: { + status: OnchainChunkStatus.CONFIRMING, + failureReason: null, + attemptCount: { increment: 1 }, + }, + }); + if (chunkChanged.count !== 1) return { unresolvedWithoutTx, confirmationStarted: false }; + await tx.blockchainProof.updateMany({ + where: { onchainChunkId: chunkId, status: ProofStatus.UNKNOWN }, + data: { status: ProofStatus.CONFIRMING, failureReason: null }, + }); + await tx.jobItem.updateMany({ + where: { chunkId, status: JobItemStatus.UNKNOWN }, + data: { status: JobItemStatus.PROCESSING, error: null }, + }); + return { unresolvedWithoutTx, confirmationStarted: true }; + }); + if (outcome.confirmationStarted) { + await enqueueOnchain(this.queue, { action: 'confirm', chunkId }); + } + return { success: true, unresolvedWithoutTx: outcome.unresolvedWithoutTx }; + } + + async markFailed(chunkId: string, dto: MarkOnchainFailedDto, user: AuthUser) { + if (user.role !== RoleType.SUPER_ADMIN) { + throw new BusinessException(ErrorCode.FORBIDDEN, '仅超级管理员可以人工确认上链失败', 403); + } + const reason = dto.reason.trim(); + const chunk = await this.prisma.onchainChunk.findUnique({ where: { id: chunkId } }); + if (!chunk) throw new BusinessException(ErrorCode.NOT_FOUND, '上链分片不存在', 404); + if (chunk.status !== OnchainChunkStatus.UNKNOWN) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '只有结果待核实的分片可以人工标记失败'); + } + await this.prisma.$transaction(async (tx) => { + const onchainCount = await tx.blockchainProof.count({ + where: { onchainChunkId: chunkId, status: ProofStatus.ONCHAIN }, + }); + const changed = await tx.onchainChunk.updateMany({ + where: { id: chunkId, status: OnchainChunkStatus.UNKNOWN }, + data: { + status: onchainCount > 0 ? OnchainChunkStatus.PARTIAL : OnchainChunkStatus.FAILED, + failureReason: `超级管理员 ${user.username} 确认失败:${reason}`, + runToken: null, + }, + }); + if (changed.count !== 1) throw new Error('上链分片状态已变化'); + await tx.blockchainProof.updateMany({ + where: { onchainChunkId: chunkId, status: { in: [ProofStatus.UNKNOWN, ProofStatus.CONFIRMING] } }, + data: { status: ProofStatus.FAILED, failureReason: reason, lastSyncedAt: new Date() }, + }); + await tx.jobItem.updateMany({ + where: { chunkId, status: { in: [JobItemStatus.UNKNOWN, JobItemStatus.PROCESSING] } }, + data: { status: JobItemStatus.FAILED, error: reason }, + }); + }); + await this.updateJobProgress(chunk.jobId); + await this.enqueueNextChunk(); + return { success: true }; + } + + private async updateJobProgress(jobId: string): Promise { + const grouped = await this.prisma.jobItem.groupBy({ + by: ['status'], + where: { jobId }, + _count: { _all: true }, + }); + const count = (status: JobItemStatus) => grouped.find((row) => row.status === status)?._count._all ?? 0; + const success = count(JobItemStatus.SUCCESS); + const failed = count(JobItemStatus.FAILED); + const remaining = count(JobItemStatus.PENDING) + count(JobItemStatus.PROCESSING) + count(JobItemStatus.UNKNOWN); + const status = remaining + ? JobStatus.PROCESSING + : failed === 0 + ? JobStatus.SUCCESS + : success + count(JobItemStatus.SKIPPED) > 0 + ? JobStatus.PARTIAL + : JobStatus.FAILED; + await this.prisma.job.update({ + where: { id: jobId }, + data: { status, successCount: success, failCount: failed, error: failed ? `${failed} 条上链失败` : null }, + }); + } + + private async enqueueNextChunk(): Promise { + const next = await this.prisma.onchainChunk.findFirst({ + where: { + status: { + in: [ + OnchainChunkStatus.PENDING, + OnchainChunkStatus.SUBMITTING, + OnchainChunkStatus.CONFIRMING, + OnchainChunkStatus.UNKNOWN, + ], + }, + }, + orderBy: [{ job: { createdAt: 'asc' } }, { jobId: 'asc' }, { sequenceNo: 'asc' }], + }); + if (next?.status === OnchainChunkStatus.PENDING) { + await enqueueOnchain(this.queue, { action: 'submit', chunkId: next.id }); + } + } } diff --git a/apps/api/src/blockchain/blockchain.controller.ts b/apps/api/src/blockchain/blockchain.controller.ts index 66e7cea..bae5d68 100644 --- a/apps/api/src/blockchain/blockchain.controller.ts +++ b/apps/api/src/blockchain/blockchain.controller.ts @@ -1,9 +1,15 @@ -import { Controller, Param, ParseIntPipe, Post } from '@nestjs/common'; +import { Body, Controller, Param, ParseIntPipe, Post } from '@nestjs/common'; import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; import { RoleType } from '@artveris/shared'; import { AttestationService } from './attestation.service'; import { Roles } from '../common/decorators/roles.decorator'; import { parseBigId } from '../common/utils/bigint.util'; +import { AuthUser, CurrentUser } from '../common/decorators/current-user.decorator'; +import { + CreateOnchainJobDto, + MarkOnchainFailedDto, + RecordOnchainTransactionDto, +} from './dto/onchain.dto'; @ApiTags('区块链存证') @ApiBearerAuth() @@ -14,15 +20,22 @@ export class BlockchainController { @Post('trace-codes/:id/onchain') @Roles(RoleType.OPERATOR) @ApiOperation({ summary: '为追溯码触发数据存证上链' }) - onchain(@Param('id') id: string) { - return this.attestation.trigger(parseBigId(id, '追溯码 ID')); + onchain(@Param('id') id: string, @CurrentUser() user: AuthUser) { + return this.attestation.trigger(parseBigId(id, '追溯码 ID'), user); + } + + @Post('blockchain/onchain-jobs') + @Roles(RoleType.OPERATOR) + @ApiOperation({ summary: '创建批量上链任务' }) + createJob(@Body() dto: CreateOnchainJobDto, @CurrentUser() user: AuthUser) { + return this.attestation.createJob(dto, user); } @Post('blockchain-proofs/:id/retry') @Roles(RoleType.OPERATOR) @ApiOperation({ summary: '重试上链' }) - retry(@Param('id', ParseIntPipe) id: number) { - return this.attestation.retry(id); + retry(@Param('id', ParseIntPipe) id: number, @CurrentUser() user: AuthUser) { + return this.attestation.retry(id, user); } @Post('blockchain-proofs/:id/confirm') @@ -31,4 +44,29 @@ export class BlockchainController { confirm(@Param('id', ParseIntPipe) id: number) { return this.attestation.confirm(id); } + + @Post('blockchain/onchain-chunks/:id/resync') + @Roles(RoleType.OPERATOR) + @ApiOperation({ summary: '使用原请求和 operateId 安全同步待核实上链分片' }) + resync(@Param('id') id: string) { + return this.attestation.resync(id); + } + + @Post('blockchain-proofs/:id/transaction') + @Roles(RoleType.OPERATOR) + @ApiOperation({ summary: '为待核实上链记录补录交易哈希' }) + recordTransaction(@Param('id', ParseIntPipe) id: number, @Body() dto: RecordOnchainTransactionDto) { + return this.attestation.recordTransaction(id, dto); + } + + @Post('blockchain/onchain-chunks/:id/mark-failed') + @Roles(RoleType.SUPER_ADMIN) + @ApiOperation({ summary: '超级管理员确认待核实分片实际失败' }) + markFailed( + @Param('id') id: string, + @Body() dto: MarkOnchainFailedDto, + @CurrentUser() user: AuthUser, + ) { + return this.attestation.markFailed(id, dto, user); + } } diff --git a/apps/api/src/blockchain/blockchain.module.ts b/apps/api/src/blockchain/blockchain.module.ts index 75cb550..52b7e9d 100644 --- a/apps/api/src/blockchain/blockchain.module.ts +++ b/apps/api/src/blockchain/blockchain.module.ts @@ -6,12 +6,13 @@ import { BlockchainService } from './blockchain.service'; import { AttestationService } from './attestation.service'; import { BlockchainController } from './blockchain.controller'; import { OnchainProcessor } from './onchain.processor'; +import { OnchainRecoveryService } from './onchain-recovery.service'; @Global() @Module({ imports: [BullModule.registerQueue({ name: QUEUE_NAMES.ONCHAIN }), SettingsModule], controllers: [BlockchainController], - providers: [BlockchainService, AttestationService, OnchainProcessor], + providers: [BlockchainService, AttestationService, OnchainProcessor, OnchainRecoveryService], exports: [BlockchainService, AttestationService], }) export class BlockchainModule {} diff --git a/apps/api/src/blockchain/blockchain.service.spec.ts b/apps/api/src/blockchain/blockchain.service.spec.ts index 4aed9da..e0e7ab8 100644 --- a/apps/api/src/blockchain/blockchain.service.spec.ts +++ b/apps/api/src/blockchain/blockchain.service.spec.ts @@ -2,9 +2,10 @@ import { ConfigService } from '@nestjs/config'; import { SettingsService } from '../settings/settings.service'; import { BlockchainService } from './blockchain.service'; -function makeService(): BlockchainService { +function makeService(baseUrl = 'https://trace.example.com'): BlockchainService { const config = { - get: (key: string) => (key === 'blockchain.driver' ? 'mock' : undefined), + get: (key: string) => + key === 'blockchain.driver' ? 'mock' : key === 'baseUrl' ? baseUrl : undefined, } as unknown as ConfigService; const settings = { getAll: async () => ({ blockchainDriver: 'mock' }), @@ -30,6 +31,22 @@ describe('BlockchainService.hashData', () => { }); }); +describe('BlockchainService.resolvePublicAssetUrl', () => { + it('将本地存储相对路径转换为部署域名下的绝对地址', () => { + const svc = makeService('https://trace.example.com/root'); + expect(svc.resolvePublicAssetUrl('/uploads/2026/07/main.jpg')).toBe( + 'https://trace.example.com/uploads/2026/07/main.jpg', + ); + }); + + it('保留 OSS/CDN 的绝对地址', () => { + const svc = makeService(); + expect(svc.resolvePublicAssetUrl('https://cdn.example.com/main.jpg')).toBe( + 'https://cdn.example.com/main.jpg', + ); + }); +}); + describe('BlockchainService.attest (mock)', () => { it('返回完整链上字段', async () => { const svc = makeService(); @@ -40,3 +57,20 @@ describe('BlockchainService.attest (mock)', () => { expect(result.explorerUrl).toContain(result.txHash); }); }); + +describe('BlockchainService.publishBatch (mock)', () => { + it('按 productId 返回逐码且可重复核对的发行结果', async () => { + const svc = makeService(); + const request = { + productIds: ['000001000001', '000002000002'], + name: '测试作品', + operateId: 'av-fixed-operation', + }; + const first = await svc.publishBatch(request); + const second = await svc.publishBatch(request); + + expect(first.products.map((item) => item.productId)).toEqual(request.productIds); + expect(first.products.map((item) => item.txHash)).toEqual(second.products.map((item) => item.txHash)); + expect(first.confirmationRequired).toBe(false); + }); +}); diff --git a/apps/api/src/blockchain/blockchain.service.ts b/apps/api/src/blockchain/blockchain.service.ts index 366b303..84a97df 100644 --- a/apps/api/src/blockchain/blockchain.service.ts +++ b/apps/api/src/blockchain/blockchain.service.ts @@ -4,7 +4,15 @@ import { createHash, randomBytes } from 'crypto'; import { ErrorCode } from '@artveris/shared'; import { BusinessException } from '../common/exceptions/business.exception'; import { SettingsService } from '../settings/settings.service'; -import { AttestPayload, AttestResult, AttestationProvider, ConfirmTransactionResult } from './blockchain.types'; +import { + AttestPayload, + AttestResult, + AttestationProvider, + BatchPublishRequest, + BatchPublishResult, + BlockchainSubmissionError, + ConfirmTransactionResult, +} from './blockchain.types'; import { MockProvider } from './mock.provider'; import { TianheProvider } from './tianhe.provider'; @@ -37,6 +45,15 @@ export class BlockchainService { return '0x' + createHash('sha256').update(stableStringify(data)).digest('hex'); } + resolvePublicAssetUrl(value: string): string { + const baseUrl = this.config.get('baseUrl') || 'http://localhost:3000'; + const url = new URL(value, `${baseUrl.replace(/\/+$/, '')}/`); + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new Error('上链作品主图必须使用可公开访问的 HTTP(S) 地址'); + } + return url.toString(); + } + async attest(payload: AttestPayload): Promise { const provider = await this.buildProvider(); this.logger.log(`区块链存证驱动:${provider.name}`); @@ -47,6 +64,46 @@ export class BlockchainService { return provider.attest(payload); } + async completeBatchPublishRequest(request: BatchPublishRequest): Promise { + const settings = await this.settings.getAllRaw(); + const driver = settings.blockchainDriver || this.config.get('blockchain.driver') || 'mock'; + if (driver !== 'tianhe') return request; + const contractAddress = (settings.tianheContractAddress || '').trim() || undefined; + const configuredMax = settings.tianheMaxTokenId?.trim() ? Number(settings.tianheMaxTokenId) : undefined; + const baseTokenId = Number.isSafeInteger(configuredMax) && configuredMax! >= 0 ? configuredMax : undefined; + return { + ...request, + contractAddress, + baseTokenId: contractAddress ? baseTokenId : undefined, + }; + } + + async publishBatch(request: BatchPublishRequest): Promise { + const provider = await this.buildProvider(); + if (!provider.publishBatch) { + throw new BlockchainSubmissionError(`区块链驱动 ${provider.name} 不支持批量发行`, false); + } + if (provider instanceof TianheProvider) await this.ensureTianheWallet(provider); + this.logger.log( + `批量发行开始:driver=${provider.name} operateId=${request.operateId} products=${request.productIds.length}`, + ); + const result = await provider.publishBatch(request); + if (provider instanceof TianheProvider && result.contractAddress) { + await this.settings.setRaw('tianheContractAddress', result.contractAddress); + } + this.logger.log( + `批量发行响应:driver=${provider.name} operateId=${request.operateId} products=${result.products.length}`, + ); + return result; + } + + async explorerTxUrl(txHash: string): Promise { + const provider = await this.buildProvider(); + return provider instanceof TianheProvider + ? provider.explorerTxUrl(txHash) + : `https://mock-explorer.local/tx/${encodeURIComponent(txHash)}`; + } + // 天河链「仅发行」:直接 publish 铸 1 个 NFT(productId=追溯码、feature=作品主图 OSS 地址)→ mint 交易经接口 9 确认拿区块信息。 // 甲方确认:不做数字商品元数据上链存储(upload),作品详情/媒体存我方 OSS;链上凭据即 NFT(tokenId + mint 交易)。 // 合约地址与已发行最大 tokenId 存系统设置(上链队列串行,无并发争用)。 diff --git a/apps/api/src/blockchain/blockchain.types.ts b/apps/api/src/blockchain/blockchain.types.ts index 9e9ab19..4ee67e7 100644 --- a/apps/api/src/blockchain/blockchain.types.ts +++ b/apps/api/src/blockchain/blockchain.types.ts @@ -21,14 +21,54 @@ export interface AttestResult { export interface ConfirmTransactionResult { confirmed: boolean; + failed?: boolean; + failureReason?: string; txHash: string; blockHash?: string | null; blockHeight?: number | null; raw: Record; } +export interface PublishProduct { + productId: string; + txHash: string; + tokenId: number | null; + blockHash?: string | null; + blockHeight?: number | null; + explorerUrl?: string | null; +} + +export interface BatchPublishRequest { + productIds: string[]; + name: string; + author?: string; + feature?: string; + contractAddress?: string; + baseTokenId?: number; + operateId: string; +} + +export interface BatchPublishResult { + contractAddress: string | null; + products: PublishProduct[]; + chainName: string; + confirmationRequired: boolean; + raw: Record; +} + +export class BlockchainSubmissionError extends Error { + constructor( + message: string, + readonly uncertain: boolean, + ) { + super(message); + this.name = 'BlockchainSubmissionError'; + } +} + export interface AttestationProvider { readonly name: string; attest(payload: AttestPayload): Promise; + publishBatch?(request: BatchPublishRequest): Promise; confirmTransaction?(txHash: string): Promise; } diff --git a/apps/api/src/blockchain/dto/onchain.dto.spec.ts b/apps/api/src/blockchain/dto/onchain.dto.spec.ts new file mode 100644 index 0000000..5ce1d8f --- /dev/null +++ b/apps/api/src/blockchain/dto/onchain.dto.spec.ts @@ -0,0 +1,20 @@ +import { plainToInstance } from 'class-transformer'; +import { validate } from 'class-validator'; +import { CreateOnchainJobDto } from './onchain.dto'; + +describe('CreateOnchainJobDto', () => { + it('IDS 选择不设置业务数量上限', async () => { + const ids = Array.from({ length: 10_001 }, (_, index) => String(index + 1)); + const dto = plainToInstance(CreateOnchainJobDto, { selection: { mode: 'IDS', ids } }); + + await expect(validate(dto)).resolves.toHaveLength(0); + }); + + it('仍拒绝非数字 ID', async () => { + const dto = plainToInstance(CreateOnchainJobDto, { + selection: { mode: 'IDS', ids: ['1', 'not-an-id'] }, + }); + + expect(await validate(dto)).not.toHaveLength(0); + }); +}); diff --git a/apps/api/src/blockchain/dto/onchain.dto.ts b/apps/api/src/blockchain/dto/onchain.dto.ts new file mode 100644 index 0000000..b2afdf6 --- /dev/null +++ b/apps/api/src/blockchain/dto/onchain.dto.ts @@ -0,0 +1,40 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { Type } from 'class-transformer'; +import { + IsOptional, + IsString, + Matches, + MaxLength, + MinLength, + ValidateNested, +} from 'class-validator'; +import { TraceCodeSelectionDto } from '../../common/dto/trace-code-selection.dto'; + +export class CreateOnchainJobDto { + @ApiProperty({ type: TraceCodeSelectionDto }) + @ValidateNested() + @Type(() => TraceCodeSelectionDto) + selection!: TraceCodeSelectionDto; +} + +export class MarkOnchainFailedDto { + @ApiProperty({ description: '确认链上实际失败的依据' }) + @IsString() + @MinLength(5) + @MaxLength(2000) + reason!: string; +} + +export class RecordOnchainTransactionDto { + @ApiProperty({ description: '天河链发行交易哈希' }) + @IsString() + @MinLength(8) + @MaxLength(191) + txHash!: string; + + @ApiProperty({ required: false, description: '已知的 tokenId,使用十进制字符串避免精度损失' }) + @IsOptional() + @IsString() + @Matches(/^\d+$/) + tokenId?: string; +} diff --git a/apps/api/src/blockchain/mock.provider.ts b/apps/api/src/blockchain/mock.provider.ts index 555a1aa..d03412f 100644 --- a/apps/api/src/blockchain/mock.provider.ts +++ b/apps/api/src/blockchain/mock.provider.ts @@ -1,5 +1,11 @@ import { createHash, randomBytes } from 'crypto'; -import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types'; +import { + AttestPayload, + AttestResult, + AttestationProvider, + BatchPublishRequest, + BatchPublishResult, +} from './blockchain.types'; // 模拟区块链存证:返回结构与真实链一致的拟真数据,便于联调与前端展示。 // 真实接入(天河链)确认后,仅需切换 BLOCKCHAIN_DRIVER=tianhe 即可替换。 @@ -31,4 +37,27 @@ export class MockProvider implements AttestationProvider { confirmationRequired: false, }; } + + async publishBatch(request: BatchPublishRequest): Promise { + const products = request.productIds.map((productId, index) => { + const txHash = `0x${createHash('sha256') + .update(`${request.operateId}:${productId}`) + .digest('hex')}`; + return { + productId, + txHash, + tokenId: (request.baseTokenId ?? 0) + index + 1, + blockHash: `0x${createHash('sha256').update(`block:${txHash}`).digest('hex')}`, + blockHeight: 8_000_000 + index, + explorerUrl: `https://mock-explorer.local/tx/${txHash}`, + }; + }); + return { + contractAddress: request.contractAddress ?? '0x0000000000000000000000000000000000000001', + products, + chainName: 'MockChain', + confirmationRequired: false, + raw: { provider: this.name, operateId: request.operateId, productCount: products.length }, + }; + } } diff --git a/apps/api/src/blockchain/onchain-recovery.service.spec.ts b/apps/api/src/blockchain/onchain-recovery.service.spec.ts new file mode 100644 index 0000000..b18f6b6 --- /dev/null +++ b/apps/api/src/blockchain/onchain-recovery.service.spec.ts @@ -0,0 +1,117 @@ +import { JobItemStatus, OnchainChunkStatus, ProofStatus } from '@prisma/client'; +import { OnchainRecoveryService } from './onchain-recovery.service'; + +describe('OnchainRecoveryService', () => { + it('UNKNOWN 自动同步达到持久化轮次上限后停止重投', async () => { + const prisma: any = { + job: { findMany: jest.fn().mockResolvedValue([]) }, + onchainChunk: { + findMany: jest.fn().mockResolvedValue([]), + findFirst: jest.fn().mockResolvedValue({ + id: 'chunk-1', + status: OnchainChunkStatus.UNKNOWN, + attemptCount: 3, + updatedAt: new Date(Date.now() - 120_000), + }), + }, + }; + const queue: any = { add: jest.fn(), setGlobalConcurrency: jest.fn() }; + const service = new OnchainRecoveryService(prisma, queue); + + await service.recover(); + + expect(queue.add).not.toHaveBeenCalled(); + }); + + it('UNKNOWN 未达上限时使用确定性 resync 任务恢复', async () => { + const prisma: any = { + job: { findMany: jest.fn().mockResolvedValue([]) }, + onchainChunk: { + findMany: jest.fn().mockResolvedValue([]), + findFirst: jest.fn().mockResolvedValue({ + id: 'chunk-1', + status: OnchainChunkStatus.UNKNOWN, + attemptCount: 2, + updatedAt: new Date(Date.now() - 120_000), + }), + }, + }; + const queue: any = { add: jest.fn().mockResolvedValue(undefined), setGlobalConcurrency: jest.fn() }; + const service = new OnchainRecoveryService(prisma, queue); + + await service.recover(); + + expect(queue.add).toHaveBeenCalledWith( + 'onchain-resync', + expect.objectContaining({ action: 'resync', chunkId: 'chunk-1' }), + expect.objectContaining({ jobId: 'onchain-resync-chunk-1' }), + ); + }); + + it('恢复旧的半认领分片时同时迁移仍为 PENDING 的 proof 和任务明细', async () => { + const tx = { + onchainChunk: { updateMany: jest.fn().mockResolvedValue({ count: 1 }) }, + blockchainProof: { updateMany: jest.fn().mockResolvedValue({ count: 1 }) }, + jobItem: { updateMany: jest.fn().mockResolvedValue({ count: 1 }) }, + }; + const prisma: any = { + job: { findMany: jest.fn().mockResolvedValue([]) }, + onchainChunk: { + findMany: jest.fn().mockResolvedValue([{ id: 'chunk-half-claimed' }]), + findFirst: jest.fn().mockResolvedValue(null), + }, + $transaction: jest.fn(async (callback: any) => callback(tx)), + }; + const queue: any = { add: jest.fn(), setGlobalConcurrency: jest.fn() }; + const service = new OnchainRecoveryService(prisma, queue); + + await service.recover(); + + expect(tx.blockchainProof.updateMany).toHaveBeenCalledWith({ + where: { + onchainChunkId: 'chunk-half-claimed', + status: { in: [ProofStatus.PENDING, ProofStatus.SUBMITTING] }, + }, + data: expect.objectContaining({ status: ProofStatus.UNKNOWN }), + }); + expect(tx.jobItem.updateMany).toHaveBeenCalledWith({ + where: { + chunkId: 'chunk-half-claimed', + status: { in: [JobItemStatus.PENDING, JobItemStatus.PROCESSING] }, + }, + data: expect.objectContaining({ status: JobItemStatus.UNKNOWN }), + }); + }); + + it('分页越过 RUNNING 任务并恢复后续待准备任务', async () => { + const running = Array.from({ length: 100 }, (_, index) => ({ + id: `job-${String(index).padStart(3, '0')}`, + payload: { phase: 'RUNNING' }, + })); + const prisma: any = { + job: { + findMany: jest.fn() + .mockResolvedValueOnce(running) + .mockResolvedValueOnce([{ id: 'job-selecting', payload: { phase: 'SELECTING' } }]), + }, + onchainChunk: { + findMany: jest.fn().mockResolvedValue([]), + findFirst: jest.fn().mockResolvedValue(null), + }, + }; + const queue: any = { add: jest.fn().mockResolvedValue(undefined), setGlobalConcurrency: jest.fn() }; + const service = new OnchainRecoveryService(prisma, queue); + + await service.recover(); + + expect(prisma.job.findMany).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ cursor: { id: 'job-099' }, skip: 1 }), + ); + expect(queue.add).toHaveBeenCalledWith( + 'onchain-prepare', + expect.objectContaining({ action: 'prepare', jobId: 'job-selecting' }), + expect.objectContaining({ jobId: 'onchain-prepare-job-selecting' }), + ); + }); +}); diff --git a/apps/api/src/blockchain/onchain-recovery.service.ts b/apps/api/src/blockchain/onchain-recovery.service.ts new file mode 100644 index 0000000..573e97b --- /dev/null +++ b/apps/api/src/blockchain/onchain-recovery.service.ts @@ -0,0 +1,133 @@ +import { InjectQueue } from '@nestjs/bullmq'; +import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; +import { Interval } from '@nestjs/schedule'; +import { JobItemStatus, JobStatus, JobType, OnchainChunkStatus, ProofStatus } from '@prisma/client'; +import { Queue } from 'bullmq'; +import { QUEUE_NAMES } from '@artveris/shared'; +import { PrismaService } from '../prisma/prisma.service'; +import { enqueueOnchain } from './onchain.queue'; + +const SUBMITTING_STALE_MS = 5 * 60_000; +const UNKNOWN_RETRY_DELAY_MS = 60_000; +const MAX_AUTOMATIC_RESYNC_ATTEMPTS = 3; + +@Injectable() +export class OnchainRecoveryService implements OnModuleInit { + private readonly logger = new Logger(OnchainRecoveryService.name); + private recovering = false; + + constructor( + private readonly prisma: PrismaService, + @InjectQueue(QUEUE_NAMES.ONCHAIN) private readonly queue: Queue, + ) {} + + async onModuleInit(): Promise { + await this.queue.setGlobalConcurrency(1); + await this.recover(); + } + + @Interval(60_000) + async recover(): Promise { + if (this.recovering) return; + this.recovering = true; + try { + await this.recoverPreparingJobs(); + await this.markInterruptedSubmissionsUnknown(); + await this.recoverFirstChunk(); + } catch (error) { + this.logger.warn(`恢复上链任务失败:${(error as Error).message}`); + } finally { + this.recovering = false; + } + } + + private async recoverPreparingJobs(): Promise { + let cursor: string | undefined; + while (true) { + const jobs = await this.prisma.job.findMany({ + where: { type: JobType.ONCHAIN, status: { in: [JobStatus.PENDING, JobStatus.PROCESSING] } }, + orderBy: { id: 'asc' }, + ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}), + take: 100, + }); + for (const job of jobs) { + const payload = job.payload && typeof job.payload === 'object' && !Array.isArray(job.payload) + ? (job.payload as Record) + : {}; + if (payload.phase === 'SELECTING' || payload.phase === 'CHUNKING' || !payload.phase) { + await enqueueOnchain(this.queue, { action: 'prepare', jobId: job.id }); + } + } + if (jobs.length < 100) break; + cursor = jobs[jobs.length - 1].id; + } + } + + private async markInterruptedSubmissionsUnknown(): Promise { + const stale = await this.prisma.onchainChunk.findMany({ + where: { + status: OnchainChunkStatus.SUBMITTING, + updatedAt: { lt: new Date(Date.now() - SUBMITTING_STALE_MS) }, + }, + select: { id: true }, + take: 20, + }); + for (const chunk of stale) { + const reason = '提交进程中断,链上请求结果待核实'; + await this.prisma.$transaction(async (tx) => { + const changed = await tx.onchainChunk.updateMany({ + where: { id: chunk.id, status: OnchainChunkStatus.SUBMITTING }, + data: { + status: OnchainChunkStatus.UNKNOWN, + runToken: null, + failureReason: reason, + unknownAt: new Date(), + }, + }); + if (changed.count !== 1) return; + await tx.blockchainProof.updateMany({ + where: { + onchainChunkId: chunk.id, + status: { in: [ProofStatus.PENDING, ProofStatus.SUBMITTING] }, + }, + data: { status: ProofStatus.UNKNOWN, failureReason: reason, lastSyncedAt: new Date() }, + }); + await tx.jobItem.updateMany({ + where: { + chunkId: chunk.id, + status: { in: [JobItemStatus.PENDING, JobItemStatus.PROCESSING] }, + }, + data: { status: JobItemStatus.UNKNOWN, error: reason }, + }); + }); + } + } + + private async recoverFirstChunk(): Promise { + const chunk = await this.prisma.onchainChunk.findFirst({ + where: { + status: { + in: [ + OnchainChunkStatus.PENDING, + OnchainChunkStatus.SUBMITTING, + OnchainChunkStatus.CONFIRMING, + OnchainChunkStatus.UNKNOWN, + ], + }, + }, + orderBy: [{ job: { createdAt: 'asc' } }, { jobId: 'asc' }, { sequenceNo: 'asc' }], + }); + if (!chunk) return; + if (chunk.status === OnchainChunkStatus.PENDING) { + await enqueueOnchain(this.queue, { action: 'submit', chunkId: chunk.id }); + } else if (chunk.status === OnchainChunkStatus.CONFIRMING) { + await enqueueOnchain(this.queue, { action: 'confirm', chunkId: chunk.id }); + } else if ( + chunk.status === OnchainChunkStatus.UNKNOWN && + chunk.attemptCount < MAX_AUTOMATIC_RESYNC_ATTEMPTS && + chunk.updatedAt.getTime() < Date.now() - UNKNOWN_RETRY_DELAY_MS + ) { + await enqueueOnchain(this.queue, { action: 'resync', chunkId: chunk.id }); + } + } +} diff --git a/apps/api/src/blockchain/onchain.helpers.spec.ts b/apps/api/src/blockchain/onchain.helpers.spec.ts new file mode 100644 index 0000000..631f897 --- /dev/null +++ b/apps/api/src/blockchain/onchain.helpers.spec.ts @@ -0,0 +1,37 @@ +import { buildAttestationSummary, firstArtworkImageKey, stableOperateId } from './onchain.helpers'; + +describe('onchain helpers', () => { + it('链上摘要只包含数字身份,不包含出库数据', () => { + const summary = buildAttestationSummary({ + shortCode: '123456000001', + archiveNo: 'A-001', + batchNo: 'B-001', + artwork: { + id: 1, + title: '测试作品', + artist: '作者', + dynamicFields: { material: '纸本' }, + traceNodes: [{ nodeType: 'CREATE', title: '创作' }], + certificates: [{ name: '收藏证书' }], + }, + }); + + expect(summary).toMatchObject({ shortCode: '123456000001', archiveNo: 'A-001', batchNo: 'B-001' }); + expect(summary).not.toHaveProperty('outbound'); + expect(summary).not.toHaveProperty('outTime'); + expect(summary).not.toHaveProperty('outImages'); + }); + + it('operateId 稳定且不超过天河链 20 字符限制', () => { + const first = stableOperateId('same-chunk-id'); + expect(first).toBe(stableOperateId('same-chunk-id')); + expect(first).toHaveLength(20); + expect(first).not.toBe(stableOperateId('other-chunk-id')); + }); + + it('拒绝 data URL 伪装为作品主图', () => { + expect(firstArtworkImageKey([{ key: '2026/07/main.jpg' }])).toBe('2026/07/main.jpg'); + expect(firstArtworkImageKey([{ key: 'data:image/png;base64,abc' }])).toBeNull(); + expect(firstArtworkImageKey([])).toBeNull(); + }); +}); diff --git a/apps/api/src/blockchain/onchain.helpers.ts b/apps/api/src/blockchain/onchain.helpers.ts new file mode 100644 index 0000000..272dcde --- /dev/null +++ b/apps/api/src/blockchain/onchain.helpers.ts @@ -0,0 +1,47 @@ +import { createHash } from 'crypto'; + +interface MediaItem { + key?: string; +} + +export interface AttestationSummaryInput { + shortCode: string; + archiveNo: string | null; + batchNo: string; + artwork: { + id: number; + title: string; + artist: string | null; + dynamicFields: unknown; + traceNodes: Array<{ nodeType: string; title: string }>; + certificates: Array<{ name: string }>; + }; +} + +export function firstArtworkImageKey(images: unknown): string | null { + const first = Array.isArray(images) ? images[0] : undefined; + const key = typeof first === 'string' ? first : (first as MediaItem | undefined)?.key; + if (!key || /^data:/i.test(key)) return null; + return key; +} + +export function buildAttestationSummary(input: AttestationSummaryInput) { + return { + shortCode: input.shortCode, + archiveNo: input.archiveNo, + batchNo: input.batchNo, + artwork: { + id: input.artwork.id, + title: input.artwork.title, + artist: input.artwork.artist, + dynamicFields: input.artwork.dynamicFields, + nodes: input.artwork.traceNodes.map((node) => ({ type: node.nodeType, title: node.title })), + certificates: input.artwork.certificates.map((certificate) => certificate.name), + }, + }; +} + +export function stableOperateId(chunkId: string): string { + return `av${createHash('sha256').update(chunkId).digest('hex').slice(0, 18)}`; +} + diff --git a/apps/api/src/blockchain/onchain.processor.spec.ts b/apps/api/src/blockchain/onchain.processor.spec.ts new file mode 100644 index 0000000..298fd9d --- /dev/null +++ b/apps/api/src/blockchain/onchain.processor.spec.ts @@ -0,0 +1,154 @@ +import { + ArtworkStatus, + AuditStatus, + JobItemStatus, + OnchainChunkStatus, + ProofStatus, + TraceCodeStatus, +} from '@prisma/client'; +import { OnchainProcessor } from './onchain.processor'; + +function makeProcessor(overrides: Record = {}) { + const tx = { + onchainChunk: { updateMany: jest.fn().mockResolvedValue({ count: 1 }) }, + blockchainProof: { updateMany: jest.fn().mockResolvedValue({ count: 1 }) }, + jobItem: { updateMany: jest.fn().mockResolvedValue({ count: 1 }) }, + $executeRaw: jest.fn().mockResolvedValue(1), + }; + const prisma: any = { + onchainChunk: { + findUnique: jest.fn(), + findFirst: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + blockchainProof: { + count: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + jobItem: { + createMany: jest.fn().mockResolvedValue({ count: 1 }), + findMany: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + $transaction: jest.fn(async (operation: unknown) => + Array.isArray(operation) ? Promise.all(operation) : (operation as (client: typeof tx) => unknown)(tx)), + ...overrides, + }; + const blockchain: any = { + completeBatchPublishRequest: jest.fn(async (request) => request), + publishBatch: jest.fn(), + resolvePublicAssetUrl: jest.fn((value: string) => value), + }; + const storage: any = {}; + const queue: any = { add: jest.fn().mockResolvedValue(undefined) }; + return { + processor: new OnchainProcessor(prisma, blockchain, storage, queue), + prisma, + blockchain, + queue, + tx, + }; +} + +describe('OnchainProcessor reliability', () => { + it('已有交易哈希的 UNKNOWN 安全同步会持久递增轮次', async () => { + const { processor, prisma, tx } = makeProcessor(); + prisma.onchainChunk.findUnique.mockResolvedValue({ id: 'chunk-1', status: OnchainChunkStatus.UNKNOWN }); + prisma.onchainChunk.findFirst.mockResolvedValue({ id: 'chunk-1' }); + prisma.blockchainProof.count.mockResolvedValue(0); + + await (processor as any).resync('chunk-1'); + + expect(tx.onchainChunk.updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ attemptCount: { increment: 1 } }), + }), + ); + expect(tx.blockchainProof.updateMany).toHaveBeenCalledWith( + expect.objectContaining({ data: expect.objectContaining({ status: ProofStatus.CONFIRMING }) }), + ); + }); + + it('提交前复检剔除的明细不会进入响应回填', async () => { + const { processor, prisma, blockchain } = makeProcessor(); + prisma.onchainChunk.findUnique.mockResolvedValue({ + id: 'chunk-1', + jobId: 'job-1', + status: OnchainChunkStatus.PENDING, + requestPayload: { + productIds: ['keep', 'drop'], + name: '作品', + feature: 'https://cdn/main.jpg', + operateId: 'av-stable-id', + }, + }); + prisma.onchainChunk.findFirst.mockResolvedValue({ id: 'chunk-1' }); + prisma.jobItem.findMany.mockResolvedValueOnce([ + { traceCodeId: 1n, shortCode: 'keep', status: JobItemStatus.PROCESSING, proof: { id: 1 } }, + ]); + blockchain.publishBatch.mockResolvedValue({ + contractAddress: '0xcontract', + products: [{ productId: 'keep', txHash: '0xtx', tokenId: 1 }], + chainName: 'MockChain', + confirmationRequired: false, + raw: { ok: true }, + }); + jest.spyOn(processor as any, 'revalidateInitialChunk').mockResolvedValue({ + request: { + productIds: ['keep'], + name: '作品', + feature: 'https://cdn/main.jpg', + operateId: 'av-stable-id', + }, + traceCodeIds: [1n], + }); + const persist = jest.spyOn(processor as any, 'persistSubmissionResults').mockResolvedValue(undefined); + jest.spyOn(processor as any, 'updateJobProgress').mockResolvedValue(undefined); + jest.spyOn(processor as any, 'enqueueNextChunk').mockResolvedValue(undefined); + + await (processor as any).submit('chunk-1', false); + + expect((processor as any).revalidateInitialChunk).toHaveBeenCalledWith( + 'chunk-1', + expect.any(Object), + expect.any(String), + ); + expect(prisma.jobItem.findMany).toHaveBeenLastCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ shortCode: { in: ['keep'] }, status: JobItemStatus.PROCESSING }), + }), + ); + expect(persist.mock.calls[0][2]).toHaveLength(1); + expect((persist.mock.calls[0][2] as Array<{ shortCode: string }>)[0].shortCode).toBe('keep'); + }); + + it('IDS 准备阶段为已删除 ID 创建失败明细并保留其余追溯码', async () => { + const { processor, prisma } = makeProcessor(); + const available = { + id: 2n, + shortCode: '482731000002', + status: TraceCodeStatus.ACTIVE, + artwork: { + status: ArtworkStatus.ACTIVE, + auditStatus: AuditStatus.APPROVED, + images: [{ key: 'main.jpg' }], + }, + proofs: [], + }; + + await (processor as any).createSelectedIdItems( + 'job-1', + [1n, 2n], + new Map([['2', available]]), + 0, + ); + + expect(prisma.jobItem.createMany).toHaveBeenCalledWith({ + data: [ + expect.objectContaining({ traceCodeId: null, selectionKey: '1', status: JobItemStatus.FAILED }), + expect.objectContaining({ traceCodeId: 2n, selectionKey: '2', status: JobItemStatus.PENDING }), + ], + skipDuplicates: true, + }); + }); +}); diff --git a/apps/api/src/blockchain/onchain.processor.ts b/apps/api/src/blockchain/onchain.processor.ts index e2de760..cfb2889 100644 --- a/apps/api/src/blockchain/onchain.processor.ts +++ b/apps/api/src/blockchain/onchain.processor.ts @@ -1,219 +1,1205 @@ import { InjectQueue, Processor, WorkerHost } from '@nestjs/bullmq'; import { Logger } from '@nestjs/common'; -import { Prisma } from '@prisma/client'; -import { Job, Queue } from 'bullmq'; -import { ProofStatus, QUEUE_NAMES } from '@artveris/shared'; +import { + ArtworkStatus, + AuditStatus, + JobItemStatus, + JobStatus, + JobType, + OnchainChunkStatus, + Prisma, + ProofStatus, + TraceCodeStatus, +} from '@prisma/client'; +import { Job as BullJob, Queue } from 'bullmq'; +import { randomUUID } from 'crypto'; +import { QUEUE_NAMES } from '@artveris/shared'; +import { TraceCodeSelectionDto } from '../common/dto/trace-code-selection.dto'; import { PrismaService } from '../prisma/prisma.service'; +import { StorageService } from '../storage/storage.service'; import { BlockchainService } from './blockchain.service'; +import { buildAttestationSummary, firstArtworkImageKey, stableOperateId } from './onchain.helpers'; +import { enqueueOnchain, OnchainQueueData } from './onchain.queue'; +import { BatchPublishRequest, BatchPublishResult, BlockchainSubmissionError } from './blockchain.types'; +import { buildOnchainSelectionWhere } from './onchain.selection'; -interface OnchainJobData { - proofId: number; - action?: 'attest' | 'confirm'; - confirmAttempt?: number; - manual?: boolean; +const SELECTION_PAGE_SIZE = 1_000; +const CHUNK_SIZE = 5_000; +const MAX_CONFIRM_ATTEMPTS = 3; + +function objectValue(value: unknown): Record { + return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : {}; } -// 自动确认延迟序列(毫秒):第 1 次提交后立即查、未到再 10s、再 30s,共 3 次;之后停等手动重新确认。 -// 第 attempt 次(从 1 起)的延迟 = AUTO_CONFIRM_DELAYS_MS[attempt - 1]。 -const AUTO_CONFIRM_DELAYS_MS = [0, 10_000, 30_000]; -const MAX_AUTO_CONFIRM_ATTEMPTS = AUTO_CONFIRM_DELAYS_MS.length; - -function requestMeta(raw: unknown): Record | undefined { - if (!raw || typeof raw !== 'object') return undefined; - const meta = (raw as Record).requestMeta; - return meta && typeof meta === 'object' ? (meta as Record) : undefined; +function jsonObject(value: unknown): Prisma.InputJsonObject { + return JSON.parse(JSON.stringify(value)) as Prisma.InputJsonObject; } -function productInfo( - raw: unknown, -): { productId: string; name: string; author?: string; feature?: string } | undefined { - if (!raw || typeof raw !== 'object') return undefined; - const product = (raw as Record).product as - | { productId?: string; name?: string; author?: string; feature?: string } - | undefined; - return product?.productId && product?.name - ? { productId: product.productId, name: product.name, author: product.author, feature: product.feature } - : undefined; +function errorMessage(error: unknown): string { + return (error instanceof Error ? error.message : String(error)).slice(0, 2_000); } -function rawObject(raw: unknown): Record { - return raw && typeof raw === 'object' ? (raw as Record) : {}; +function hasTraceCode( + item: T, +): item is T & { traceCodeId: bigint; traceCode: NonNullable } { + return item.traceCodeId !== null && item.traceCode !== null; } -function jsonObject(value: Record): Prisma.InputJsonObject { - return value as Prisma.InputJsonObject; +function parseBatchRequest(value: unknown): BatchPublishRequest { + const raw = objectValue(value); + const productIds = Array.isArray(raw.productIds) + ? raw.productIds.filter((item): item is string => typeof item === 'string') + : []; + if (!productIds.length || typeof raw.name !== 'string' || typeof raw.operateId !== 'string') { + throw new Error('上链分片缺少完整的持久化请求参数'); + } + return { + productIds, + name: raw.name, + ...(typeof raw.author === 'string' ? { author: raw.author } : {}), + ...(typeof raw.feature === 'string' ? { feature: raw.feature } : {}), + ...(typeof raw.contractAddress === 'string' ? { contractAddress: raw.contractAddress } : {}), + ...(typeof raw.baseTokenId === 'number' ? { baseTokenId: raw.baseTokenId } : {}), + operateId: raw.operateId, + }; } -@Processor(QUEUE_NAMES.ONCHAIN) +@Processor(QUEUE_NAMES.ONCHAIN, { concurrency: 1 }) export class OnchainProcessor extends WorkerHost { private readonly logger = new Logger(OnchainProcessor.name); constructor( private readonly prisma: PrismaService, private readonly blockchain: BlockchainService, + private readonly storage: StorageService, @InjectQueue(QUEUE_NAMES.ONCHAIN) private readonly queue: Queue, ) { super(); } - async process(job: Job): Promise { - if (job.data.action === 'confirm') { - await this.confirm(job.data.proofId, job.data.confirmAttempt || 1, Boolean(job.data.manual)); - return; + async process(job: BullJob): Promise { + switch (job.data.action) { + case 'prepare': + if (job.data.jobId) await this.prepare(job.data.jobId); + return; + case 'submit': + if (job.data.chunkId) await this.submit(job.data.chunkId, false); + return; + case 'resync': + if (job.data.chunkId) await this.resync(job.data.chunkId); + return; + case 'confirm': + if (job.data.chunkId) await this.confirm(job.data.chunkId, job.attemptsMade + 1); + return; } - await this.attest(job.data.proofId); } - private async attest(proofId: number): Promise { - const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } }); - if (!proof) return; + private async prepare(jobId: string): Promise { + const record = await this.prisma.job.findUnique({ where: { id: jobId } }); + if (!record || record.type !== JobType.ONCHAIN) return; + if ( + record.status === JobStatus.SUCCESS || + record.status === JobStatus.PARTIAL || + record.status === JobStatus.FAILED + ) return; try { - const result = await this.blockchain.attest({ - dataHash: proof.dataHash, - meta: requestMeta(proof.rawResponse), - product: productInfo(proof.rawResponse), - }); - await this.prisma.blockchainProof.update({ - where: { id: proofId }, - data: { - status: result.confirmationRequired ? ProofStatus.CONFIRMING : ProofStatus.ONCHAIN, - txHash: result.txHash, - blockHash: result.blockHash || null, - blockHeight: result.blockHeight !== null && result.blockHeight !== undefined ? BigInt(result.blockHeight) : null, - chainName: result.chainName, - explorerUrl: result.explorerUrl || null, - tokenId: result.tokenId !== null && result.tokenId !== undefined ? BigInt(result.tokenId) : null, - contractAddress: result.contractAddress || null, - onchainAt: result.confirmationRequired ? null : result.onchainAt, - rawResponse: jsonObject({ - ...(result.raw as object), - submittedAt: new Date().toISOString(), - }), - }, - }); - if (result.confirmationRequired) { - // 提交完立即发起第 1 次确认查询(delay=0) - await this.scheduleConfirm(proofId, 1, AUTO_CONFIRM_DELAYS_MS[0]); - this.logger.log(`存证 ${proofId} 已提交链上,等待确认:txHash=${result.txHash} 存证链接=${result.explorerUrl ?? '-'}`); - } else { - this.logger.log(`存证 ${proofId} 上链成功:txHash=${result.txHash} blockHeight=${result.blockHeight ?? '-'}`); + await this.prisma.job.update({ where: { id: jobId }, data: { status: JobStatus.PROCESSING } }); + let payload = objectValue(record.payload); + const phase = typeof payload.phase === 'string' ? payload.phase : 'SELECTING'; + if (phase === 'SELECTING') { + await this.prepareSelectionItems(jobId, payload); + payload = await this.setPhase(jobId, 'CHUNKING'); } - } catch (e) { - const message = (e as Error).message; - await this.prisma.blockchainProof.update({ - where: { id: proofId }, - data: { - status: ProofStatus.FAILED, - rawResponse: jsonObject({ - ...(proof.rawResponse && typeof proof.rawResponse === 'object' ? (proof.rawResponse as object) : {}), - error: message, - failedAt: new Date().toISOString(), - }), - }, - }); - this.logger.error(`存证 ${proofId} 上链失败: ${message}`); + if (payload.phase === 'CHUNKING') { + await this.prepareChunks(jobId); + await this.setPhase(jobId, 'RUNNING'); + } + await this.updateJobProgress(jobId); + await this.enqueueNextChunk(); + } catch (error) { + const message = `上链任务准备失败:${errorMessage(error)}`; + await this.failPreparation(jobId, message); + this.logger.error(`job=${jobId} ${message}`); } } - private async confirm(proofId: number, attempt: number, manual = false): Promise { - const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } }); - if (!proof || proof.status === ProofStatus.ONCHAIN) return; - if (proof.status !== ProofStatus.CONFIRMING && !manual) return; - if (!proof.txHash) { - await this.markConfirmFailed(proofId, proof.rawResponse, '缺少交易哈希,无法确认链上结果', attempt); + private async prepareSelectionItems(jobId: string, payload: Record): Promise { + const selection = payload.selection as unknown as TraceCodeSelectionDto; + if (!selection?.mode) throw new Error('任务缺少追溯码选择条件'); + const snapshotMaxId = typeof payload.snapshotMaxId === 'string' ? BigInt(payload.snapshotMaxId) : null; + if (!snapshotMaxId) throw new Error('任务缺少选择快照边界'); + const { where: selectionWhere, orderedIds, excludedIds } = buildOnchainSelectionWhere(selection); + const excluded = new Set(excludedIds); + let sequence = 0; + + if (orderedIds) { + for (let offset = 0; offset < orderedIds.length; offset += SELECTION_PAGE_SIZE) { + const ids = orderedIds.slice(offset, offset + SELECTION_PAGE_SIZE); + const codes = await this.loadSelectionCodes({ id: { in: ids } }); + const byId = new Map(codes.map((code) => [code.id.toString(), code])); + await this.createSelectedIdItems(jobId, ids, byId, sequence); + sequence += ids.length; + } + if (!sequence) throw new Error('没有可处理的追溯码'); return; } - this.logger.log(`存证 ${proofId} 开始链上确认查询(第 ${attempt} 次${manual ? ',手动' : ''}):txHash=${proof.txHash}`); - try { - const result = await this.blockchain.confirmTransaction(proof.txHash); - this.logger.log( - `存证 ${proofId} 链上查询结果:confirmed=${result.confirmed} blockHash=${result.blockHash ?? '-'} ` + - `blockHeight=${result.blockHeight ?? '-'} status=${(result.raw as { status?: string })?.status ?? '-'} ` + - `响应=${JSON.stringify((result.raw as { response?: unknown })?.response ?? result.raw).slice(0, 300)}`, - ); - if (result.confirmed) { - // 发行时 tokenId=-1(待处理)的场景:确认查询返回真实 tokenId 后回填 - const confirmedTokenId = Number((result.raw as { tokenId?: string | number })?.tokenId ?? NaN); - await this.prisma.blockchainProof.update({ - where: { id: proofId }, - data: { - status: ProofStatus.ONCHAIN, - txHash: result.txHash, - blockHash: result.blockHash || proof.blockHash || null, - blockHeight: - result.blockHeight !== null && result.blockHeight !== undefined - ? BigInt(result.blockHeight) - : proof.blockHeight, - tokenId: - proof.tokenId ?? (Number.isInteger(confirmedTokenId) && confirmedTokenId >= 0 ? BigInt(confirmedTokenId) : null), - onchainAt: new Date(), - rawResponse: jsonObject({ - ...rawObject(proof.rawResponse), - confirmation: result.raw, - confirmationAttempts: attempt, - confirmedAt: new Date().toISOString(), + let cursor: bigint | undefined; + while (true) { + const pageCodes = await this.loadSelectionCodes({ + AND: [selectionWhere, { id: { lte: snapshotMaxId } }, ...(cursor ? [{ id: { gt: cursor } }] : [])], + }); + if (!pageCodes.length) break; + const codes = pageCodes.filter((code) => !excluded.has(code.id)); + await this.createInitialItems(jobId, codes, sequence); + sequence += codes.length; + cursor = pageCodes[pageCodes.length - 1].id; + if (pageCodes.length < SELECTION_PAGE_SIZE) break; + } + if (!sequence) throw new Error('没有可处理的追溯码'); + } + + private loadSelectionCodes(where: Prisma.TraceCodeWhereInput) { + return this.prisma.traceCode.findMany({ + where, + include: { + artwork: { select: { status: true, auditStatus: true, images: true } }, + proofs: { select: { id: true, status: true }, take: 1 }, + }, + orderBy: { id: 'asc' }, + take: SELECTION_PAGE_SIZE, + }); + } + + private async createInitialItems(jobId: string, codes: Array, offset: number): Promise { + if (!codes.length) return; + await this.prisma.jobItem.createMany({ + data: codes.map((code, index) => { + const reason = this.ineligibilityReason(code); + return { + jobId, + traceCodeId: code.id, + selectionKey: code.id.toString(), + shortCode: code.shortCode, + sequence: offset + index, + status: reason ? JobItemStatus.SKIPPED : JobItemStatus.PENDING, + payload: jsonObject({ + traceStatus: code.status, + artworkStatus: code.artwork.status, + auditStatus: code.artwork.auditStatus, + }), + ...(reason ? { result: jsonObject({ reason }) } : {}), + }; + }), + skipDuplicates: true, + }); + } + + private async createSelectedIdItems( + jobId: string, + ids: bigint[], + byId: Map, + offset: number, + ): Promise { + await this.prisma.jobItem.createMany({ + data: ids.map((id, index) => { + const code = byId.get(id.toString()); + if (!code) { + return { + jobId, + traceCodeId: null, + selectionKey: id.toString(), + shortCode: `ID:${id.toString()}`, + sequence: offset + index, + status: JobItemStatus.FAILED, + error: '追溯码在任务准备前已不存在', + result: jsonObject({ requestedId: id.toString(), reason: '追溯码在任务准备前已不存在' }), + }; + } + const reason = this.ineligibilityReason(code); + return { + jobId, + traceCodeId: code.id, + selectionKey: code.id.toString(), + shortCode: code.shortCode, + sequence: offset + index, + status: reason ? JobItemStatus.SKIPPED : JobItemStatus.PENDING, + payload: jsonObject({ + traceStatus: code.status, + artworkStatus: code.artwork.status, + auditStatus: code.artwork.auditStatus, + }), + ...(reason ? { result: jsonObject({ reason }) } : {}), + }; + }), + skipDuplicates: true, + }); + } + + private ineligibilityReason(code: any): string | null { + if (![TraceCodeStatus.INACTIVE, TraceCodeStatus.ACTIVE].includes(code.status)) return '追溯码状态不允许上链'; + if (code.artwork.status !== ArtworkStatus.ACTIVE) return '所属作品未启用'; + if (code.artwork.auditStatus !== AuditStatus.APPROVED) return '所属作品尚未审核通过'; + if (!firstArtworkImageKey(code.artwork.images)) return '所属作品缺少真实主图'; + const proof = code.proofs?.[0]; + if (proof && proof.status !== ProofStatus.FAILED) { + if (proof.status === ProofStatus.ONCHAIN) return '该追溯码已经上链'; + if (proof.status === ProofStatus.UNKNOWN) return '该追溯码上链结果待核实,禁止重新铸造'; + return '该追溯码正在上链处理中'; + } + return null; + } + + private async prepareChunks(jobId: string): Promise { + const maxSequence = await this.prisma.onchainChunk.aggregate({ where: { jobId }, _max: { sequenceNo: true } }); + let sequenceNo = (maxSequence._max.sequenceNo ?? 0) + 1; + while (true) { + const items = await this.prisma.jobItem.findMany({ + where: { jobId, status: JobItemStatus.PENDING, chunkId: null }, + include: { + traceCode: { + include: { + batch: true, + proofs: { take: 1 }, + artwork: { include: { traceNodes: true, certificates: true } }, + }, + }, + }, + orderBy: [{ sequence: 'asc' }, { id: 'asc' }], + take: CHUNK_SIZE, + }); + if (!items.length) break; + const attachedItems = items.filter(hasTraceCode); + const groups = new Map(); + for (const item of attachedItems) { + const group = groups.get(item.traceCode.artworkId) ?? []; + group.push(item); + groups.set(item.traceCode.artworkId, group); + } + for (const group of groups.values()) { + if (await this.createChunk(jobId, sequenceNo, group)) sequenceNo += 1; + } + } + const total = await this.prisma.jobItem.count({ where: { jobId } }); + await this.prisma.job.update({ where: { id: jobId }, data: { total } }); + } + + private async createChunk(jobId: string, sequenceNo: number, sourceItems: Array): Promise { + const itemIds = sourceItems.map((item) => item.id); + const traceCodeIds = sourceItems.map((item) => item.traceCodeId); + return this.prisma.$transaction( + async (tx) => { + await tx.$queryRaw( + Prisma.sql`SELECT id FROM trace_code WHERE id IN (${Prisma.join(traceCodeIds)}) FOR UPDATE`, + ); + await tx.$queryRaw( + Prisma.sql`SELECT id FROM artwork WHERE id = ${sourceItems[0].traceCode.artworkId} FOR UPDATE`, + ); + const items = await tx.jobItem.findMany({ + where: { id: { in: itemIds }, status: JobItemStatus.PENDING, chunkId: null }, + include: { + traceCode: { + include: { + batch: true, + proofs: { take: 1 }, + artwork: { include: { traceNodes: true, certificates: true } }, + }, + }, + }, + orderBy: [{ sequence: 'asc' }, { id: 'asc' }], + }); + const attachedItems = items.filter(hasTraceCode); + const eligible: Array<{ item: (typeof attachedItems)[number]; summary: Record; feature: string }> = []; + for (const item of attachedItems) { + const reason = this.ineligibilityReason(item.traceCode); + const imageKey = firstArtworkImageKey(item.traceCode.artwork.images); + if (reason || !imageKey) { + await tx.jobItem.update({ + where: { id: item.id }, + data: { status: JobItemStatus.SKIPPED, result: jsonObject({ reason: reason || '所属作品缺少真实主图' }) }, + }); + continue; + } + eligible.push({ + item, + feature: this.blockchain.resolvePublicAssetUrl(this.storage.getUrl(imageKey)), + summary: buildAttestationSummary({ + shortCode: item.shortCode, + archiveNo: item.traceCode.artwork.archiveNo, + batchNo: item.traceCode.batch.batchNo, + artwork: item.traceCode.artwork, }), + }); + } + if (!eligible.length) return false; + + const artwork = eligible[0].item.traceCode.artwork; + if (eligible.some((entry) => entry.item.traceCode.artworkId !== artwork.id)) { + throw new Error('同一上链分片包含不同作品'); + } + const id = randomUUID(); + const operateId = stableOperateId(id); + const feature = eligible[0].feature.slice(0, 500); + const productIds = eligible.map((entry) => entry.item.shortCode); + const request: BatchPublishRequest = { + productIds, + name: artwork.title.slice(0, 42), + ...(artwork.artist ? { author: artwork.artist.slice(0, 120) } : {}), + feature, + operateId, + }; + await tx.onchainChunk.create({ + data: { + id, + jobId, + artworkId: artwork.id, + sequenceNo, + operateId, + productIds, + metadataSnapshot: jsonObject({ + artworkId: artwork.id, + title: artwork.title, + artist: artwork.artist, + archiveNo: artwork.archiveNo, + dynamicFields: artwork.dynamicFields, + feature, + }), + requestPayload: jsonObject(request), }, }); - this.logger.log(`存证 ${proofId} 链上确认成功`); - return; - } - await this.recordWaiting(proofId, proof.rawResponse, result.raw, attempt, manual); - if (manual || attempt >= MAX_AUTO_CONFIRM_ATTEMPTS) { - this.logger.warn(`存证 ${proofId} 尚未查询到链上确认信息,等待手动重新确认`); - return; - } - await this.scheduleConfirm(proofId, attempt + 1, AUTO_CONFIRM_DELAYS_MS[attempt]); - } catch (e) { - const message = (e as Error).message; - this.logger.warn(`存证 ${proofId} 链上确认查询失败(第 ${attempt} 次):${message}`); - await this.recordWaiting(proofId, proof.rawResponse, { error: message }, attempt, manual); - if (manual || attempt >= MAX_AUTO_CONFIRM_ATTEMPTS) { - this.logger.warn(`存证 ${proofId} 自动确认已达上限,等待手动重新确认`); - return; - } - await this.scheduleConfirm(proofId, attempt + 1, AUTO_CONFIRM_DELAYS_MS[attempt]); - } - } - - private scheduleConfirm(proofId: number, confirmAttempt: number, delay: number, manual = false) { - return this.queue.add( - 'confirm-onchain', - { proofId, action: 'confirm', confirmAttempt, manual } satisfies OnchainJobData, - { delay }, + const existingByCode = new Map( + eligible + .map((entry) => entry.item.traceCode.proofs?.[0]) + .filter(Boolean) + .map((proof) => [proof.traceCodeId.toString(), proof]), + ); + const newProofs = eligible + .filter((entry) => !existingByCode.has(entry.item.traceCodeId.toString())) + .map((entry) => ({ + traceCodeId: entry.item.traceCodeId, + dataHash: this.blockchain.hashData(entry.summary), + status: ProofStatus.PENDING, + onchainChunkId: id, + rawResponse: jsonObject({ + requestMeta: entry.summary, + product: { + productId: entry.item.shortCode, + name: request.name, + author: request.author, + feature, + }, + operateId, + }), + })); + if (newProofs.length) await tx.blockchainProof.createMany({ data: newProofs }); + for (const entry of eligible) { + const existing = existingByCode.get(entry.item.traceCodeId.toString()); + if (!existing) continue; + const reset = await tx.blockchainProof.updateMany({ + where: { id: existing.id, status: ProofStatus.FAILED }, + data: { + dataHash: this.blockchain.hashData(entry.summary), + status: ProofStatus.PENDING, + onchainChunkId: id, + txHash: null, + blockHash: null, + blockHeight: null, + chainName: null, + explorerUrl: null, + tokenId: null, + contractAddress: null, + submittedAt: null, + onchainAt: null, + failureReason: null, + lastSyncedAt: null, + rawResponse: jsonObject({ + requestMeta: entry.summary, + product: { + productId: entry.item.shortCode, + name: request.name, + author: request.author, + feature, + }, + operateId, + retryOf: { proofId: existing.id, failedAt: existing.updatedAt.toISOString() }, + }), + }, + }); + if (reset.count !== 1) throw new Error(`追溯码 ${entry.item.shortCode} 的上链状态已变化`); + } + const proofs = await tx.blockchainProof.findMany({ where: { traceCodeId: { in: traceCodeIds } } }); + const proofByCode = new Map(proofs.map((proof) => [proof.traceCodeId.toString(), proof])); + for (const entry of eligible) { + const proof = proofByCode.get(entry.item.traceCodeId.toString()); + if (!proof) throw new Error(`追溯码 ${entry.item.shortCode} 的上链记录创建失败`); + } + const eligibleItemIds = eligible.map((entry) => entry.item.id); + await tx.jobItem.updateMany({ + where: { id: { in: eligibleItemIds } }, + data: { chunkId: id, payload: jsonObject({ operateId }) }, + }); + await tx.$executeRaw( + Prisma.sql` + UPDATE job_item AS item + INNER JOIN blockchain_proof AS proof ON proof.trace_code_id = item.trace_code_id + SET item.proof_id = proof.id + WHERE item.id IN (${Prisma.join(eligibleItemIds)}) + `, + ); + return true; + }, + { timeout: 120_000 }, ); } - private recordWaiting(proofId: number, raw: unknown, confirmation: Record, attempt: number, manual: boolean) { - return this.prisma.blockchainProof.update({ - where: { id: proofId }, - data: { - status: ProofStatus.CONFIRMING, - rawResponse: jsonObject({ - ...rawObject(raw), - confirmation, - confirmationAttempts: attempt, - confirmationManualRequired: manual || attempt >= MAX_AUTO_CONFIRM_ATTEMPTS, - lastConfirmMode: manual ? 'manual' : 'auto', - lastConfirmCheckedAt: new Date().toISOString(), + private async submit(chunkId: string, resync: boolean): Promise { + const chunk = await this.prisma.onchainChunk.findUnique({ where: { id: chunkId } }); + if (!chunk) return; + const expectedStatus = resync ? OnchainChunkStatus.UNKNOWN : OnchainChunkStatus.PENDING; + if (chunk.status !== expectedStatus) return; + if (!(await this.isGlobalTurn(chunkId))) return; + + let request = parseBatchRequest(chunk.requestPayload); + const runToken = randomUUID(); + let selectedTraceCodeIds: bigint[]; + if (!resync) { + try { + request = await this.blockchain.completeBatchPublishRequest(request); + const revalidated = await this.revalidateInitialChunk(chunkId, request, runToken); + if (!revalidated) { + await this.updateJobProgress(chunk.jobId); + await this.enqueueNextChunk(); + return; + } + request = revalidated.request; + selectedTraceCodeIds = revalidated.traceCodeIds; + } catch (error) { + await this.failPendingChunk(chunk, errorMessage(error)); + return; + } + } else { + const selectedItems = await this.prisma.jobItem.findMany({ + where: { chunkId, shortCode: { in: request.productIds } }, + select: { traceCodeId: true }, + }); + if (selectedItems.length !== request.productIds.length) { + this.logger.error(`待核实分片明细不完整,停止安全同步:chunk=${chunkId}`); + return; + } + if (selectedItems.some((item) => item.traceCodeId === null)) { + this.logger.error(`待核实分片包含无追溯码明细,停止安全同步:chunk=${chunkId}`); + return; + } + selectedTraceCodeIds = selectedItems.map((item) => item.traceCodeId as bigint); + const claimed = await this.prisma.$transaction(async (tx) => { + const chunkClaim = await tx.onchainChunk.updateMany({ + where: { id: chunkId, status: expectedStatus }, + data: { + status: OnchainChunkStatus.SUBMITTING, + runToken, + requestPayload: jsonObject(request), + baseTokenId: request.baseTokenId !== undefined ? BigInt(request.baseTokenId) : null, + attemptCount: { increment: 1 }, + submittedAt: new Date(), + failureReason: null, + }, + }); + if (chunkClaim.count !== 1) return false; + await tx.blockchainProof.updateMany({ + where: { + onchainChunkId: chunkId, + traceCodeId: { in: selectedTraceCodeIds }, + status: { in: [ProofStatus.PENDING, ProofStatus.UNKNOWN, ProofStatus.FAILED] }, + }, + data: { status: ProofStatus.SUBMITTING, failureReason: null, submittedAt: new Date() }, + }); + await tx.jobItem.updateMany({ + where: { + chunkId, + shortCode: { in: request.productIds }, + status: { in: [JobItemStatus.PENDING, JobItemStatus.UNKNOWN, JobItemStatus.FAILED] }, + }, + data: { status: JobItemStatus.PROCESSING, error: null }, + }); + return true; + }); + if (!claimed) return; + } + + let responseReceived = false; + try { + const result = await this.blockchain.publishBatch(request); + responseReceived = true; + const byProductId = new Map(result.products.map((product) => [product.productId, product])); + if (request.productIds.some((id) => !byProductId.get(id)?.txHash)) { + throw new BlockchainSubmissionError('发行响应未完整覆盖持久化 productId 列表', true); + } + const items = await this.prisma.jobItem.findMany({ + where: { chunkId, shortCode: { in: request.productIds }, status: JobItemStatus.PROCESSING }, + include: { proof: true }, + }); + if (items.length !== request.productIds.length) { + throw new BlockchainSubmissionError('发行响应对应的任务明细发生变化', true); + } + if (items.some((item) => item.traceCodeId === null)) { + throw new BlockchainSubmissionError('发行响应包含无追溯码任务明细', true); + } + const submissionItems = items as Array<(typeof items)[number] & { traceCodeId: bigint }>; + const now = new Date(); + await this.prisma.$transaction( + async (tx) => { + const updated = await tx.onchainChunk.updateMany({ + where: { id: chunkId, status: OnchainChunkStatus.SUBMITTING, runToken }, + data: { + status: result.confirmationRequired ? OnchainChunkStatus.CONFIRMING : OnchainChunkStatus.SUCCESS, + runToken: null, + response: jsonObject(result.raw), + txHash: result.products[0]?.txHash ?? null, + contractAddress: result.contractAddress, + confirmedAt: result.confirmationRequired ? null : now, + failureReason: null, + }, + }); + if (updated.count !== 1) throw new Error('上链分片处理权已失效'); + await this.persistSubmissionResults(tx, chunkId, submissionItems, byProductId, result, now); + }, + { timeout: 120_000 }, + ); + this.logger.log( + `上链分片已提交:chunk=${chunkId} operateId=${request.operateId} products=${request.productIds.length}`, + ); + if (result.confirmationRequired) { + await enqueueOnchain(this.queue, { action: 'confirm', chunkId }); + } else { + await this.updateJobProgress(chunk.jobId); + await this.enqueueNextChunk(); + } + } catch (error) { + const uncertain = responseReceived || !(error instanceof BlockchainSubmissionError) || error.uncertain; + await this.markSubmissionError(chunk, runToken, errorMessage(error), uncertain); + if (!uncertain) await this.enqueueNextChunk(); + } + } + + private async revalidateInitialChunk( + chunkId: string, + currentRequest: BatchPublishRequest, + runToken: string, + ): Promise<{ request: BatchPublishRequest; traceCodeIds: bigint[] } | null> { + return this.prisma.$transaction( + async (tx) => { + await tx.$queryRaw( + Prisma.sql`SELECT id FROM onchain_chunk WHERE id = ${chunkId} FOR UPDATE`, + ); + const currentChunk = await tx.onchainChunk.findUnique({ where: { id: chunkId } }); + if (!currentChunk || currentChunk.status !== OnchainChunkStatus.PENDING) return null; + await tx.$queryRaw( + Prisma.sql` + SELECT code.id + FROM trace_code AS code + INNER JOIN job_item AS item ON item.trace_code_id = code.id + WHERE item.chunk_id = ${chunkId} + ORDER BY code.id + FOR UPDATE + `, + ); + await tx.$queryRaw( + Prisma.sql`SELECT id FROM artwork WHERE id = ${currentChunk.artworkId} FOR UPDATE`, + ); + const itemRows = await tx.jobItem.findMany({ + where: { chunkId }, + include: { + proof: true, + traceCode: { + include: { + batch: true, + artwork: { include: { traceNodes: true, certificates: true } }, + }, + }, + }, + orderBy: [{ sequence: 'asc' }, { id: 'asc' }], + }); + const valid: Array<(typeof itemRows)[number] & { + traceCodeId: bigint; + traceCode: NonNullable<(typeof itemRows)[number]['traceCode']>; + }> = []; + for (const item of itemRows) { + if (!hasTraceCode(item)) { + await tx.jobItem.update({ + where: { id: item.id }, + data: { status: JobItemStatus.FAILED, error: '任务明细关联的追溯码已不存在' }, + }); + continue; + } + let reason: string | null = null; + if ( + item.traceCode.status !== TraceCodeStatus.INACTIVE && + item.traceCode.status !== TraceCodeStatus.ACTIVE + ) { + reason = '提交前复检发现追溯码状态不允许上链'; + } else if (item.traceCode.artwork.status !== ArtworkStatus.ACTIVE) { + reason = '提交前复检发现所属作品未启用'; + } else if (item.traceCode.artwork.auditStatus !== AuditStatus.APPROVED) { + reason = '提交前复检发现所属作品尚未审核通过'; + } else if (!firstArtworkImageKey(item.traceCode.artwork.images)) { + reason = '提交前复检发现所属作品缺少真实主图'; + } else if ( + !item.proof || + item.proof.onchainChunkId !== chunkId || + item.proof.status !== ProofStatus.PENDING + ) { + reason = '提交前复检发现上链记录状态已变化'; + } + if (!reason) { + valid.push(item); + continue; + } + await tx.jobItem.update({ + where: { id: item.id }, + data: { status: JobItemStatus.SKIPPED, result: jsonObject({ reason }), error: null }, + }); + if (item.proof?.status === ProofStatus.PENDING) { + await tx.blockchainProof.update({ + where: { id: item.proof.id }, + data: { status: ProofStatus.FAILED, failureReason: reason }, + }); + } + } + if (!valid.length) { + await tx.onchainChunk.update({ + where: { id: chunkId }, + data: { status: OnchainChunkStatus.FAILED, failureReason: '提交前复检后没有可上链的追溯码' }, + }); + return null; + } + const artwork = valid[0].traceCode.artwork; + const imageKey = firstArtworkImageKey(artwork.images)!; + const feature = this.blockchain.resolvePublicAssetUrl(this.storage.getUrl(imageKey)).slice(0, 500); + const request: BatchPublishRequest = { + ...currentRequest, + productIds: valid.map((item) => item.shortCode), + name: artwork.title.slice(0, 42), + ...(artwork.artist ? { author: artwork.artist.slice(0, 120) } : { author: undefined }), + feature, + }; + for (const item of valid) { + const summary = buildAttestationSummary({ + shortCode: item.shortCode, + archiveNo: artwork.archiveNo, + batchNo: item.traceCode.batch.batchNo, + artwork, + }); + await tx.blockchainProof.update({ + where: { id: item.proof!.id }, + data: { + dataHash: this.blockchain.hashData(summary), + rawResponse: jsonObject({ + ...objectValue(item.proof!.rawResponse), + requestMeta: summary, + product: { + productId: item.shortCode, + name: request.name, + author: request.author, + feature, + }, + }), + }, + }); + } + const traceCodeIds = valid.map((item) => item.traceCodeId); + const now = new Date(); + const claimed = await tx.onchainChunk.updateMany({ + where: { id: chunkId, status: OnchainChunkStatus.PENDING }, + data: { + status: OnchainChunkStatus.SUBMITTING, + runToken, + productIds: request.productIds, + requestPayload: jsonObject(request), + baseTokenId: request.baseTokenId !== undefined ? BigInt(request.baseTokenId) : null, + metadataSnapshot: jsonObject({ + artworkId: artwork.id, + title: artwork.title, + artist: artwork.artist, + archiveNo: artwork.archiveNo, + dynamicFields: artwork.dynamicFields, + feature, + }), + attemptCount: { increment: 1 }, + submittedAt: now, + failureReason: null, + }, + }); + if (claimed.count !== 1) throw new Error('上链分片处理权已失效'); + const proofsClaimed = await tx.blockchainProof.updateMany({ + where: { + onchainChunkId: chunkId, + traceCodeId: { in: traceCodeIds }, + status: ProofStatus.PENDING, + }, + data: { status: ProofStatus.SUBMITTING, failureReason: null, submittedAt: now }, + }); + const itemsClaimed = await tx.jobItem.updateMany({ + where: { + id: { in: valid.map((item) => item.id) }, + status: JobItemStatus.PENDING, + }, + data: { status: JobItemStatus.PROCESSING, error: null }, + }); + if (proofsClaimed.count !== valid.length || itemsClaimed.count !== valid.length) { + throw new Error('上链分片明细状态已变化'); + } + return { request, traceCodeIds }; + }, + { timeout: 120_000 }, + ); + } + + private async persistSubmissionResults( + tx: Prisma.TransactionClient, + chunkId: string, + items: Array<{ traceCodeId: bigint; shortCode: string; proof: { id: number } | null }>, + byProductId: Map, + result: BatchPublishResult, + now: Date, + ): Promise { + for (let offset = 0; offset < items.length; offset += 250) { + const rows = items.slice(offset, offset + 250).map((item) => ({ + traceCodeId: item.traceCodeId, + product: byProductId.get(item.shortCode)!, + })); + const ids = rows.map((row) => row.traceCodeId); + const txHashCases = rows.map((row) => Prisma.sql`WHEN ${row.traceCodeId} THEN ${row.product.txHash}`); + const blockHashCases = rows.map((row) => Prisma.sql`WHEN ${row.traceCodeId} THEN ${row.product.blockHash ?? null}`); + const blockHeightCases = rows.map((row) => Prisma.sql` + WHEN ${row.traceCodeId} THEN ${ + row.product.blockHeight !== null && row.product.blockHeight !== undefined + ? BigInt(row.product.blockHeight) + : null + } + `); + const explorerCases = rows.map((row) => Prisma.sql`WHEN ${row.traceCodeId} THEN ${row.product.explorerUrl ?? null}`); + const tokenCases = rows.map((row) => Prisma.sql` + WHEN ${row.traceCodeId} THEN ${row.product.tokenId !== null ? BigInt(row.product.tokenId) : null} + `); + const resultCases = rows.map((row) => Prisma.sql` + WHEN ${row.traceCodeId} THEN ${JSON.stringify({ txHash: row.product.txHash, tokenId: row.product.tokenId })} + `); + const proofStatus = result.confirmationRequired ? ProofStatus.CONFIRMING : ProofStatus.ONCHAIN; + const itemStatus = result.confirmationRequired ? JobItemStatus.PROCESSING : JobItemStatus.SUCCESS; + await tx.$executeRaw( + Prisma.sql` + UPDATE blockchain_proof + SET status = ${proofStatus}, + tx_hash = CASE trace_code_id ${Prisma.join(txHashCases, ' ')} ELSE tx_hash END, + block_hash = CASE trace_code_id ${Prisma.join(blockHashCases, ' ')} ELSE block_hash END, + block_height = CASE trace_code_id ${Prisma.join(blockHeightCases, ' ')} ELSE block_height END, + explorer_url = CASE trace_code_id ${Prisma.join(explorerCases, ' ')} ELSE explorer_url END, + token_id = CASE trace_code_id ${Prisma.join(tokenCases, ' ')} ELSE token_id END, + chain_name = ${result.chainName}, + contract_address = ${result.contractAddress}, + submitted_at = ${now}, + onchain_at = ${result.confirmationRequired ? null : now}, + last_synced_at = ${now}, + failure_reason = NULL, + raw_response = JSON_SET(COALESCE(raw_response, JSON_OBJECT()), '$.submittedAt', ${now.toISOString()}) + WHERE onchain_chunk_id = ${chunkId} + AND status = ${ProofStatus.SUBMITTING} + AND trace_code_id IN (${Prisma.join(ids)}) + `, + ); + await tx.$executeRaw( + Prisma.sql` + UPDATE job_item + SET status = ${itemStatus}, + result = CASE trace_code_id ${Prisma.join(resultCases, ' ')} ELSE result END, + error = NULL + WHERE chunk_id = ${chunkId} + AND trace_code_id IN (${Prisma.join(ids)}) + `, + ); + } + } + + private async resync(chunkId: string): Promise { + const chunk = await this.prisma.onchainChunk.findUnique({ where: { id: chunkId } }); + if (!chunk || chunk.status !== OnchainChunkStatus.UNKNOWN) return; + if (!(await this.isGlobalTurn(chunkId))) return; + const missingHashes = await this.prisma.blockchainProof.count({ + where: { onchainChunkId: chunkId, status: ProofStatus.UNKNOWN, txHash: null }, + }); + if (missingHashes > 0) { + await this.submit(chunkId, true); + return; + } + const changed = await this.prisma.$transaction(async (tx) => { + const claimed = await tx.onchainChunk.updateMany({ + where: { id: chunkId, status: OnchainChunkStatus.UNKNOWN }, + data: { status: OnchainChunkStatus.CONFIRMING, failureReason: null, attemptCount: { increment: 1 } }, + }); + if (claimed.count !== 1) return false; + await tx.blockchainProof.updateMany({ + where: { onchainChunkId: chunkId, status: ProofStatus.UNKNOWN }, + data: { status: ProofStatus.CONFIRMING, failureReason: null }, + }); + await tx.jobItem.updateMany({ + where: { chunkId, status: JobItemStatus.UNKNOWN }, + data: { status: JobItemStatus.PROCESSING, error: null }, + }); + return true; + }); + if (!changed) return; + await enqueueOnchain(this.queue, { action: 'confirm', chunkId }); + } + + private async confirm(chunkId: string, attempt: number): Promise { + const chunk = await this.prisma.onchainChunk.findUnique({ where: { id: chunkId } }); + if (!chunk || chunk.status !== OnchainChunkStatus.CONFIRMING) return; + if (!(await this.isGlobalTurn(chunkId))) return; + const proofs = await this.prisma.blockchainProof.findMany({ + where: { onchainChunkId: chunkId, status: ProofStatus.CONFIRMING }, + include: { jobItems: { where: { chunkId }, take: 1 } }, + orderBy: { id: 'asc' }, + }); + for (const proof of proofs) { + if (!proof.txHash) continue; + try { + const result = await this.blockchain.confirmTransaction(proof.txHash); + const now = new Date(); + if (result.confirmed) { + const tokenValue = (result.raw as { tokenId?: string | number }).tokenId; + const tokenId = tokenValue !== undefined && /^\d+$/.test(String(tokenValue)) ? BigInt(String(tokenValue)) : null; + await this.prisma.$transaction([ + this.prisma.blockchainProof.update({ + where: { id: proof.id }, + data: { + status: ProofStatus.ONCHAIN, + txHash: result.txHash, + blockHash: result.blockHash ?? proof.blockHash, + blockHeight: result.blockHeight !== null && result.blockHeight !== undefined + ? BigInt(result.blockHeight) + : proof.blockHeight, + tokenId: tokenId ?? proof.tokenId, + onchainAt: now, + lastSyncedAt: now, + failureReason: null, + rawResponse: jsonObject({ + ...objectValue(proof.rawResponse), + confirmation: result.raw, + confirmationAttempts: attempt, + confirmedAt: now.toISOString(), + }), + }, + }), + this.prisma.jobItem.updateMany({ + where: { proofId: proof.id, chunkId }, + data: { + status: JobItemStatus.SUCCESS, + result: jsonObject({ txHash: result.txHash, tokenId: tokenId?.toString() ?? proof.tokenId?.toString() }), + error: null, + }, + }), + ]); + } else if (result.failed) { + const reason = result.failureReason || '链上交易执行失败'; + await this.prisma.$transaction([ + this.prisma.blockchainProof.update({ + where: { id: proof.id }, + data: { + status: ProofStatus.FAILED, + failureReason: reason, + lastSyncedAt: now, + rawResponse: jsonObject({ + ...objectValue(proof.rawResponse), + confirmation: result.raw, + confirmationAttempts: attempt, + }), + }, + }), + this.prisma.jobItem.updateMany({ + where: { proofId: proof.id, chunkId }, + data: { status: JobItemStatus.FAILED, error: reason }, + }), + ]); + } else { + await this.prisma.blockchainProof.update({ + where: { id: proof.id }, + data: { + lastSyncedAt: now, + rawResponse: jsonObject({ + ...objectValue(proof.rawResponse), + confirmation: result.raw, + confirmationAttempts: attempt, + lastConfirmCheckedAt: now.toISOString(), + }), + }, + }); + } + } catch (error) { + await this.prisma.blockchainProof.update({ + where: { id: proof.id }, + data: { + lastSyncedAt: new Date(), + rawResponse: jsonObject({ + ...objectValue(proof.rawResponse), + confirmationError: errorMessage(error), + confirmationAttempts: attempt, + lastConfirmCheckedAt: new Date().toISOString(), + }), + }, + }); + } + } + + const remaining = await this.prisma.blockchainProof.count({ + where: { onchainChunkId: chunkId, status: ProofStatus.CONFIRMING }, + }); + if (remaining > 0) { + if (attempt < MAX_CONFIRM_ATTEMPTS) throw new Error(`上链分片 ${chunkId} 等待第 ${attempt + 1} 次确认`); + const reason = `连续 ${MAX_CONFIRM_ATTEMPTS} 次仍无法确认链上结果`; + await this.prisma.$transaction([ + this.prisma.blockchainProof.updateMany({ + where: { onchainChunkId: chunkId, status: ProofStatus.CONFIRMING }, + data: { status: ProofStatus.UNKNOWN, failureReason: reason, lastSyncedAt: new Date() }, }), + this.prisma.jobItem.updateMany({ + where: { chunkId, status: JobItemStatus.PROCESSING }, + data: { status: JobItemStatus.UNKNOWN, error: reason }, + }), + this.prisma.onchainChunk.update({ + where: { id: chunkId }, + data: { status: OnchainChunkStatus.UNKNOWN, failureReason: reason, unknownAt: new Date(), runToken: null }, + }), + ]); + await this.updateJobProgress(chunk.jobId); + this.logger.warn(`上链分片待核实:chunk=${chunkId} remaining=${remaining}`); + return; + } + await this.finishConfirmedChunk(chunkId, chunk.jobId); + } + + private async finishConfirmedChunk(chunkId: string, jobId: string): Promise { + const grouped = await this.prisma.blockchainProof.groupBy({ + by: ['status'], + where: { onchainChunkId: chunkId }, + _count: { _all: true }, + }); + const count = (status: ProofStatus) => grouped.find((row) => row.status === status)?._count._all ?? 0; + const success = count(ProofStatus.ONCHAIN); + const failed = count(ProofStatus.FAILED); + const unknown = count(ProofStatus.UNKNOWN); + const nonTerminal = count(ProofStatus.PENDING) + count(ProofStatus.SUBMITTING) + count(ProofStatus.CONFIRMING); + if (nonTerminal > 0) { + const reason = `${nonTerminal} 个追溯码的上链状态未完成,结果待核实`; + await this.prisma.$transaction([ + this.prisma.blockchainProof.updateMany({ + where: { + onchainChunkId: chunkId, + status: { in: [ProofStatus.PENDING, ProofStatus.SUBMITTING, ProofStatus.CONFIRMING] }, + }, + data: { status: ProofStatus.UNKNOWN, failureReason: reason, lastSyncedAt: new Date() }, + }), + this.prisma.jobItem.updateMany({ + where: { chunkId, status: { in: [JobItemStatus.PENDING, JobItemStatus.PROCESSING] } }, + data: { status: JobItemStatus.UNKNOWN, error: reason }, + }), + this.prisma.onchainChunk.update({ + where: { id: chunkId }, + data: { status: OnchainChunkStatus.UNKNOWN, unknownAt: new Date(), failureReason: reason, runToken: null }, + }), + ]); + await this.updateJobProgress(jobId); + return; + } + if (unknown > 0) { + await this.prisma.onchainChunk.update({ + where: { id: chunkId }, + data: { + status: OnchainChunkStatus.UNKNOWN, + unknownAt: new Date(), + failureReason: `${unknown} 个追溯码的链上结果待核实`, + }, + }); + await this.updateJobProgress(jobId); + return; + } + const status = failed === 0 + ? OnchainChunkStatus.SUCCESS + : success > 0 + ? OnchainChunkStatus.PARTIAL + : OnchainChunkStatus.FAILED; + await this.prisma.onchainChunk.update({ + where: { id: chunkId }, + data: { + status, + confirmedAt: new Date(), + runToken: null, + failureReason: failed ? `${failed} 个追溯码的链上交易失败` : null, + }, + }); + await this.updateJobProgress(jobId); + await this.enqueueNextChunk(); + this.logger.log(`上链分片确认完成:chunk=${chunkId} success=${success} failed=${failed}`); + } + + private async markSubmissionError( + chunk: { id: string; jobId: string }, + runToken: string, + reason: string, + uncertain: boolean, + ): Promise { + const chunkStatus = uncertain ? OnchainChunkStatus.UNKNOWN : OnchainChunkStatus.FAILED; + const proofStatus = uncertain ? ProofStatus.UNKNOWN : ProofStatus.FAILED; + const itemStatus = uncertain ? JobItemStatus.UNKNOWN : JobItemStatus.FAILED; + const applied = await this.prisma.$transaction(async (tx) => { + const changed = await tx.onchainChunk.updateMany({ + where: { id: chunk.id, status: OnchainChunkStatus.SUBMITTING, runToken }, + data: { + status: chunkStatus, + runToken: null, + failureReason: reason, + ...(uncertain ? { unknownAt: new Date() } : {}), + }, + }); + if (changed.count !== 1) return false; + await tx.blockchainProof.updateMany({ + where: { onchainChunkId: chunk.id, status: { in: [ProofStatus.PENDING, ProofStatus.SUBMITTING] } }, + data: { status: proofStatus, failureReason: reason, lastSyncedAt: new Date() }, + }); + await tx.jobItem.updateMany({ + where: { chunkId: chunk.id, status: { in: [JobItemStatus.PENDING, JobItemStatus.PROCESSING] } }, + data: { status: itemStatus, error: reason }, + }); + return true; + }); + if (!applied) return; + await this.updateJobProgress(chunk.jobId); + const level = uncertain ? 'warn' : 'error'; + this.logger[level](`上链分片${uncertain ? '结果待核实' : '失败'}:chunk=${chunk.id} ${reason}`); + } + + private async failPendingChunk(chunk: { id: string; jobId: string }, reason: string): Promise { + const applied = await this.prisma.$transaction(async (tx) => { + const changed = await tx.onchainChunk.updateMany({ + where: { id: chunk.id, status: OnchainChunkStatus.PENDING }, + data: { status: OnchainChunkStatus.FAILED, failureReason: reason }, + }); + if (changed.count !== 1) return false; + await tx.blockchainProof.updateMany({ + where: { onchainChunkId: chunk.id, status: ProofStatus.PENDING }, + data: { status: ProofStatus.FAILED, failureReason: reason }, + }); + await tx.jobItem.updateMany({ + where: { chunkId: chunk.id, status: JobItemStatus.PENDING }, + data: { status: JobItemStatus.FAILED, error: reason }, + }); + return true; + }); + if (!applied) return; + await this.updateJobProgress(chunk.jobId); + await this.enqueueNextChunk(); + } + + private async isGlobalTurn(chunkId: string): Promise { + const first = await this.prisma.onchainChunk.findFirst({ + where: { + status: { + in: [ + OnchainChunkStatus.PENDING, + OnchainChunkStatus.SUBMITTING, + OnchainChunkStatus.CONFIRMING, + OnchainChunkStatus.UNKNOWN, + ], + }, + }, + orderBy: [{ job: { createdAt: 'asc' } }, { jobId: 'asc' }, { sequenceNo: 'asc' }], + select: { id: true }, + }); + return first?.id === chunkId; + } + + private async enqueueNextChunk(): Promise { + const next = await this.prisma.onchainChunk.findFirst({ + where: { + status: { + in: [ + OnchainChunkStatus.PENDING, + OnchainChunkStatus.SUBMITTING, + OnchainChunkStatus.CONFIRMING, + OnchainChunkStatus.UNKNOWN, + ], + }, + }, + orderBy: [{ job: { createdAt: 'asc' } }, { jobId: 'asc' }, { sequenceNo: 'asc' }], + }); + if (next?.status === OnchainChunkStatus.PENDING) { + await enqueueOnchain(this.queue, { action: 'submit', chunkId: next.id }); + } + } + + private async updateJobProgress(jobId: string): Promise { + const grouped = await this.prisma.jobItem.groupBy({ + by: ['status'], + where: { jobId }, + _count: { _all: true }, + }); + const count = (status: JobItemStatus) => grouped.find((row) => row.status === status)?._count._all ?? 0; + const success = count(JobItemStatus.SUCCESS); + const failed = count(JobItemStatus.FAILED); + const skipped = count(JobItemStatus.SKIPPED); + const remaining = count(JobItemStatus.PENDING) + count(JobItemStatus.PROCESSING) + count(JobItemStatus.UNKNOWN); + const status = remaining + ? JobStatus.PROCESSING + : failed === 0 + ? JobStatus.SUCCESS + : success + skipped > 0 + ? JobStatus.PARTIAL + : JobStatus.FAILED; + await this.prisma.job.update({ + where: { id: jobId }, + data: { + status, + successCount: success, + failCount: failed, + error: failed ? `${failed} 条上链失败` : null, }, }); } - private markConfirmFailed(proofId: number, raw: unknown, message: string, attempt: number) { - return this.prisma.blockchainProof.update({ - where: { id: proofId }, + private async setPhase(jobId: string, phase: string): Promise> { + const job = await this.prisma.job.findUniqueOrThrow({ where: { id: jobId } }); + const payload = { ...objectValue(job.payload), phase }; + await this.prisma.job.update({ where: { id: jobId }, data: { payload: jsonObject(payload) } }); + return payload; + } + + private async failPreparation(jobId: string, reason: string): Promise { + await this.prisma.$transaction([ + this.prisma.jobItem.updateMany({ + where: { jobId, status: { in: [JobItemStatus.PENDING, JobItemStatus.PROCESSING] } }, + data: { status: JobItemStatus.FAILED, error: reason }, + }), + this.prisma.blockchainProof.updateMany({ + where: { onchainChunk: { is: { jobId, status: OnchainChunkStatus.PENDING } }, status: ProofStatus.PENDING }, + data: { status: ProofStatus.FAILED, failureReason: reason }, + }), + this.prisma.onchainChunk.updateMany({ + where: { jobId, status: OnchainChunkStatus.PENDING }, + data: { status: OnchainChunkStatus.FAILED, failureReason: reason }, + }), + ]); + const [failed, total, job] = await this.prisma.$transaction([ + this.prisma.jobItem.count({ where: { jobId, status: JobItemStatus.FAILED } }), + this.prisma.jobItem.count({ where: { jobId } }), + this.prisma.job.findUnique({ where: { id: jobId }, select: { total: true } }), + ]); + await this.prisma.job.update({ + where: { id: jobId }, data: { - status: ProofStatus.FAILED, - rawResponse: jsonObject({ - ...rawObject(raw), - confirmationError: message, - confirmationAttempts: attempt, - failedAt: new Date().toISOString(), - }), + status: JobStatus.FAILED, + total: Math.max(job?.total ?? 0, total), + failCount: failed, + error: reason, }, }); } diff --git a/apps/api/src/blockchain/onchain.queue.ts b/apps/api/src/blockchain/onchain.queue.ts new file mode 100644 index 0000000..6ae1dab --- /dev/null +++ b/apps/api/src/blockchain/onchain.queue.ts @@ -0,0 +1,29 @@ +import { Queue } from 'bullmq'; + +export type OnchainQueueAction = 'prepare' | 'submit' | 'confirm' | 'resync'; + +export interface OnchainQueueData { + action: OnchainQueueAction; + jobId?: string; + chunkId?: string; +} + +export function onchainBullJobId(data: OnchainQueueData): string { + const target = data.chunkId ?? data.jobId; + if (!target) throw new Error('上链队列任务缺少目标 ID'); + return `onchain-${data.action}-${target}`; +} + +export async function enqueueOnchain( + queue: Queue, + data: OnchainQueueData, + delay = 0, +): Promise { + await queue.add(`onchain-${data.action}`, data, { + jobId: onchainBullJobId(data), + delay, + removeOnComplete: true, + removeOnFail: true, + ...(data.action === 'confirm' ? { attempts: 3, backoff: { type: 'exponential', delay: 10_000 } } : {}), + }); +} diff --git a/apps/api/src/blockchain/onchain.selection.spec.ts b/apps/api/src/blockchain/onchain.selection.spec.ts new file mode 100644 index 0000000..c69e206 --- /dev/null +++ b/apps/api/src/blockchain/onchain.selection.spec.ts @@ -0,0 +1,26 @@ +import { TraceCodeStatus } from '@artveris/shared'; +import { buildOnchainSelectionWhere } from './onchain.selection'; + +describe('buildOnchainSelectionWhere', () => { + it.each([TraceCodeStatus.INACTIVE, TraceCodeStatus.ACTIVE])( + 'ELIGIBLE 保留显式追溯码状态 %s', + (status) => { + const result = buildOnchainSelectionWhere({ + mode: 'FILTER', + filters: { proofStatus: 'ELIGIBLE', status }, + }); + expect(result.where.status).toBe(status); + }, + ); + + it.each([TraceCodeStatus.DISABLED, TraceCodeStatus.ABNORMAL])( + 'ELIGIBLE 与不可上链状态 %s 组合时返回空状态集合', + (status) => { + const result = buildOnchainSelectionWhere({ + mode: 'FILTER', + filters: { proofStatus: 'ELIGIBLE', status }, + }); + expect(result.where.status).toEqual({ in: [] }); + }, + ); +}); diff --git a/apps/api/src/blockchain/onchain.selection.ts b/apps/api/src/blockchain/onchain.selection.ts new file mode 100644 index 0000000..d1dd235 --- /dev/null +++ b/apps/api/src/blockchain/onchain.selection.ts @@ -0,0 +1,18 @@ +import { Prisma, TraceCodeStatus } from '@prisma/client'; +import { TraceCodeSelectionDto } from '../common/dto/trace-code-selection.dto'; +import { buildTraceCodeSelectionWhere } from '../common/utils/trace-code-selection.util'; + +export function buildOnchainSelectionWhere(selection: TraceCodeSelectionDto): { + where: Prisma.TraceCodeWhereInput; + orderedIds: bigint[] | null; + excludedIds: bigint[]; +} { + const result = buildTraceCodeSelectionWhere(selection); + const filter = selection.mode === 'FILTER' ? selection.filters : undefined; + if (filter?.proofStatus === 'ELIGIBLE' && filter.status) { + result.where.status = filter.status === TraceCodeStatus.INACTIVE || filter.status === TraceCodeStatus.ACTIVE + ? filter.status + : { in: [] }; + } + return result; +} diff --git a/apps/api/src/blockchain/tianhe.provider.spec.ts b/apps/api/src/blockchain/tianhe.provider.spec.ts index 389caac..13b77f9 100644 --- a/apps/api/src/blockchain/tianhe.provider.spec.ts +++ b/apps/api/src/blockchain/tianhe.provider.spec.ts @@ -133,6 +133,110 @@ describe('TianheProvider', () => { expect(result.address).toBe('0xwallet'); }); + it('原生批量发行使用 productIds 和 pieceCount,并按 productId 回填', async () => { + const fetchMock = jest.spyOn(globalThis, 'fetch').mockResolvedValue({ + ok: true, + status: 200, + text: async () => + JSON.stringify({ + code: 0, + data: { + contractAddress: '0xcontract', + products: [ + { productId: '000002000002', transactionHash: '0xtx2', tokenId: 12 }, + { productId: '000001000001', transactionHash: '0xtx1', tokenId: 11 }, + ], + }, + }), + } as Response); + + const result = await provider.publishBatch({ + productIds: ['000001000001', '000002000002'], + name: '批量发行测试', + feature: 'https://cdn.example.com/main.jpg', + operateId: 'av-batch-fixed-id', + }); + + const body = JSON.parse(String(fetchMock.mock.calls[0][1]?.body)); + expect(body.productIds).toEqual(['000001000001', '000002000002']); + expect(body.pieceCount).toBe(2); + expect(body.operateId).toBe('av-batch-fixed-id'); + expect(result.products.map((item) => item.productId)).toEqual(body.productIds); + expect(result.products.map((item) => item.txHash)).toEqual(['0xtx1', '0xtx2']); + expect(result.confirmationRequired).toBe(true); + }); + + it('批量发行响应缺少 productId 时标记为不确定结果', async () => { + jest.spyOn(globalThis, 'fetch').mockResolvedValue({ + ok: true, + status: 200, + text: async () => + JSON.stringify({ + code: 0, + data: { + contractAddress: '0xcontract', + products: [{ productId: '000001000001', transactionHash: '0xtx1', tokenId: 11 }], + }, + }), + } as Response); + + await expect( + provider.publishBatch({ + productIds: ['000001000001', '000002000002'], + name: '批量发行测试', + operateId: 'av-batch-incomplete', + }), + ).rejects.toMatchObject({ uncertain: true }); + }); + + it('HTTP 200 但业务响应无法确认时保持 UNKNOWN 语义', async () => { + jest.spyOn(globalThis, 'fetch').mockResolvedValue({ + ok: true, + status: 200, + text: async () => JSON.stringify({ data: { accepted: true } }), + } as Response); + + await expect( + provider.publishBatch({ + productIds: ['000001000001'], + name: '批量发行测试', + operateId: 'av-batch-ambiguous', + }), + ).rejects.toMatchObject({ uncertain: true }); + }); + + it.each([408, 409, 425, 429])('HTTP %s 按可能已受理处理,禁止直接重铸', async (status) => { + jest.spyOn(globalThis, 'fetch').mockResolvedValue({ + ok: false, + status, + text: async () => JSON.stringify({ message: 'request state unknown' }), + } as Response); + + await expect( + provider.publishBatch({ + productIds: ['000001000001'], + name: '批量发行测试', + operateId: 'av-batch-http-edge', + }), + ).rejects.toMatchObject({ uncertain: true }); + }); + + it('HTTP 400 明确拒绝时允许按失败处理', async () => { + jest.spyOn(globalThis, 'fetch').mockResolvedValue({ + ok: false, + status: 400, + text: async () => JSON.stringify({ message: 'invalid request' }), + } as Response); + + await expect( + provider.publishBatch({ + productIds: ['000001000001'], + name: '批量发行测试', + operateId: 'av-batch-http-400', + }), + ).rejects.toMatchObject({ uncertain: false }); + }); + it('ensureRegistered 优先查询接口 8,失败则回退注册', async () => { const fetchMock = jest .spyOn(globalThis, 'fetch') @@ -151,6 +255,178 @@ describe('TianheProvider', () => { expect(String(fetchMock.mock.calls[1][0])).toContain('/api/v2/user'); }); + it('请求和响应日志递归遮蔽大小写不同的钱包密钥', async () => { + const appKey = 'raw-app-key-secret'; + const userKey = 'raw-user-key-secret'; + const newUserKey = 'raw-new-user-key-secret'; + const secureProvider = new TianheProvider({ + baseUrl: 'https://test.api.tichain.tianhecloud.com', + appId: 'app-id', + appKey, + userId: 'user-id', + userKey, + }); + const logSpy = jest.spyOn((secureProvider as any).logger, 'log').mockImplementation(() => undefined); + jest.spyOn(globalThis, 'fetch').mockResolvedValue({ + ok: true, + status: 200, + text: async () => + JSON.stringify({ + code: 0, + data: { + NEW_USER_KEY: newUserKey, + nested: { APPKEY: appKey, UserKey: userKey }, + message: `rotated ${newUserKey}`, + }, + }), + } as Response); + + await secureProvider.updateUserKey(newUserKey); + + const output = logSpy.mock.calls.flat().join('\n'); + expect(output).toContain('***'); + expect(output).not.toContain(appKey); + expect(output).not.toContain(userKey); + expect(output).not.toContain(newUserKey); + }); + + it('成功响应即使回显钱包密钥也不会进入持久化 raw 结果', async () => { + const appKey = 'persist-app-key-secret'; + const userKey = 'persist-user-key-secret'; + const secureProvider = new TianheProvider({ + baseUrl: 'https://test.api.tichain.tianhecloud.com', + appId: 'app-id', + appKey, + userId: 'user-id', + userKey, + }); + jest.spyOn(globalThis, 'fetch').mockResolvedValue({ + ok: true, + status: 200, + text: async () => JSON.stringify({ + code: 0, + message: `accepted with ${appKey}`, + data: { + contractAddress: '0xcontract', + products: [{ productId: '000001000001', transactionHash: '0xtx', tokenId: 1 }], + nested: { USER_KEY: userKey, detail: `echo ${appKey} ${userKey}` }, + }, + }), + } as Response); + + const publish = await secureProvider.publishBatch({ + productIds: ['000001000001'], + name: '密钥清洗测试', + operateId: 'av-redact-raw', + }); + const publishRaw = JSON.stringify(publish.raw); + expect(publishRaw).toContain('***'); + expect(publishRaw).not.toContain(appKey); + expect(publishRaw).not.toContain(userKey); + + mockHttpsRequestOnce({ + code: 0, + message: `confirmed with ${appKey}`, + data: { + status: '0x0', + blockHash: '0xblock', + blockNum: 1, + transactionHash: '0xtx', + userKey, + }, + }); + const confirmation = await secureProvider.confirmTransaction('0xtx'); + const confirmationRaw = JSON.stringify(confirmation.raw); + expect(confirmationRaw).toContain('***'); + expect(confirmationRaw).not.toContain(appKey); + expect(confirmationRaw).not.toContain(userKey); + }); + + it('HTTP 和业务错误在抛出前遮蔽轮换请求的全部密钥', async () => { + const appKey = 'http-business-app-secret'; + const userKey = 'http-business-user-secret'; + const newUserKey = `${userKey}-rotated`; + const secureProvider = new TianheProvider({ + baseUrl: 'https://test.api.tichain.tianhecloud.com', + appId: 'app-id', + appKey, + userId: 'user-id', + userKey, + }); + jest.spyOn(globalThis, 'fetch') + .mockResolvedValueOnce({ + ok: false, + status: 502, + text: async () => JSON.stringify({ message: `${'x'.repeat(175)}${appKey} ${userKey} ${newUserKey}` }), + } as Response) + .mockResolvedValueOnce({ + ok: true, + status: 200, + text: async () => + JSON.stringify({ + code: 500, + message: `business echoed ${appKey} ${userKey} ${newUserKey}`, + }), + } as Response); + + const messages: string[] = []; + for (let attempt = 0; attempt < 2; attempt += 1) { + try { + await secureProvider.updateUserKey(newUserKey); + } catch (error) { + messages.push((error as Error).message); + } + } + + expect(messages).toHaveLength(2); + expect(messages.join('\n')).not.toContain(appKey.slice(0, 10)); + expect(messages.join('\n')).not.toContain('-rotated'); + for (const message of messages) { + expect(message).toContain('***'); + expect(message).not.toContain(appKey); + expect(message).not.toContain(userKey); + expect(message).not.toContain(newUserKey); + } + }); + + it('multipart 和原生 GET 的 HTTP 错误不回显请求密钥', async () => { + const appKey = 'transport-app-secret'; + const userKey = 'transport-user-secret'; + const secureProvider = new TianheProvider({ + baseUrl: 'https://test.api.tichain.tianhecloud.com', + appId: 'app-id', + appKey, + userId: 'user-id', + userKey, + }); + jest.spyOn(globalThis, 'fetch').mockResolvedValue({ + ok: false, + status: 502, + text: async () => JSON.stringify({ message: `upload echoed ${appKey} ${userKey}` }), + } as Response); + + const messages: string[] = []; + try { + await secureProvider.attest({ dataHash: '0xtransport' }); + } catch (error) { + messages.push((error as Error).message); + } + + mockHttpsRequestOnce({ message: `confirm echoed ${appKey} ${userKey}` }, 502); + try { + await secureProvider.confirmTransaction('0xtransport'); + } catch (error) { + messages.push((error as Error).message); + } + + expect(messages).toHaveLength(2); + for (const message of messages) { + expect(message).toContain('***'); + expect(message).not.toContain(appKey); + expect(message).not.toContain(userKey); + } + }); + it('按交易状态接口确认链上区块信息(GET+body 走 https 模块)', async () => { const response = { code: 0, diff --git a/apps/api/src/blockchain/tianhe.provider.ts b/apps/api/src/blockchain/tianhe.provider.ts index 22e0bf5..acd44c7 100644 --- a/apps/api/src/blockchain/tianhe.provider.ts +++ b/apps/api/src/blockchain/tianhe.provider.ts @@ -2,7 +2,23 @@ import { Logger } from '@nestjs/common'; import { randomBytes } from 'crypto'; import { request as httpRequest } from 'node:http'; import { request as httpsRequest } from 'node:https'; -import { AttestPayload, AttestResult, AttestationProvider, ConfirmTransactionResult } from './blockchain.types'; +import { + AttestPayload, + AttestResult, + AttestationProvider, + BatchPublishRequest, + BatchPublishResult, + BlockchainSubmissionError, + ConfirmTransactionResult, +} from './blockchain.types'; + +const REQUEST_TIMEOUT_MS = 30_000; +const MAX_PUBLISH_PRODUCTS = 5_000; +const UNCERTAIN_HTTP_STATUSES = new Set([408, 409, 425, 429]); + +function isUncertainHttpStatus(status: number): boolean { + return status >= 500 || UNCERTAIN_HTTP_STATUSES.has(status); +} export interface TianheOptions { baseUrl: string; @@ -59,18 +75,78 @@ function assertOk(raw: Record, action: string): Record) : {}; } -// 天河链 API 链路日志:打印 URL / 方法 / 发送数据 / 返回结果,appKey/userKey 脱敏 -function redactSecrets(obj: Record): Record { - const masked: Record = { ...obj }; - for (const key of ['appKey', 'userKey']) { - const v = masked[key]; - if (typeof v === 'string' && v) { - masked[key] = v.length > 8 ? `${v.slice(0, 3)}***${v.slice(-3)}` : '***'; - } +// 天河链 API 链路日志:请求和响应中的钱包密钥一律完整遮蔽。 +const TIANHE_SECRET_KEYS = new Set(['appkey', 'userkey', 'newuserkey']); + +function normalizedKey(key: string): string { + return key.replace(/[^a-z0-9]/gi, '').toLowerCase(); +} + +function redactSecrets(value: unknown): unknown { + if (Array.isArray(value)) return value.map(redactSecrets); + if (!value || typeof value !== 'object') return value; + + const masked: Record = {}; + for (const [key, child] of Object.entries(value as Record)) { + masked[key] = TIANHE_SECRET_KEYS.has(normalizedKey(key)) ? '***' : redactSecrets(child); } return masked; } +function collectSecretValues(value: unknown, result: string[] = []): string[] { + if (Array.isArray(value)) { + for (const child of value) collectSecretValues(child, result); + return result; + } + if (!value || typeof value !== 'object') return result; + + for (const [key, child] of Object.entries(value as Record)) { + if (TIANHE_SECRET_KEYS.has(normalizedKey(key)) && typeof child === 'string' && child) { + result.push(child); + } else { + collectSecretValues(child, result); + } + } + return result; +} + +function replaceSecretValues(text: string, secrets: string[]): string { + let safe = text; + const orderedSecrets = [...new Set(secrets)].sort((left, right) => right.length - left.length); + for (const secret of orderedSecrets) { + safe = safe.split(secret).join('***'); + const jsonEncoded = JSON.stringify(secret).slice(1, -1); + if (jsonEncoded !== secret) safe = safe.split(jsonEncoded).join('***'); + } + return safe; +} + +function replaceSecretValuesDeep(value: unknown, secrets: string[]): unknown { + if (typeof value === 'string') return replaceSecretValues(value, secrets); + if (Array.isArray(value)) return value.map((child) => replaceSecretValuesDeep(child, secrets)); + if (!value || typeof value !== 'object') return value; + + return Object.fromEntries( + Object.entries(value as Record).map(([key, child]) => [ + key, + replaceSecretValuesDeep(child, secrets), + ]), + ); +} + +function summarizePayload(obj: Record): Record { + const redacted = redactSecrets(obj) as Record; + const ids = redacted.productIds; + if (Array.isArray(ids)) { + redacted.productIds = { + count: ids.length, + first: ids.slice(0, 3), + last: ids.length > 3 ? ids.slice(-3) : [], + }; + } + return redacted; +} + export function buildTianheExplorerTxUrl(baseUrl: string, txHash: string, environment?: string): string { const testEnvironment = environment === 'test' || (environment !== 'production' && baseUrl.toLowerCase().includes('test.')); @@ -86,12 +162,46 @@ export class TianheProvider implements AttestationProvider { constructor(private readonly opts: TianheOptions) {} - private logRequest(method: string, url: string, payload: unknown): void { - this.logger.log(`→ ${method} ${url} 发送=${JSON.stringify(payload)}`); + private secretValues(requestPayload?: unknown): string[] { + return [ + this.opts.appKey, + this.opts.userKey, + ...collectSecretValues(requestPayload), + ].filter(Boolean); } - private logResponse(method: string, url: string, status: number, text: string): void { - this.logger.log(`← ${method} ${url} HTTP ${status} 返回=${text.slice(0, 500)}`); + private redactText(text: string, requestPayload?: unknown): string { + const secrets = this.secretValues(requestPayload); + return replaceSecretValues(text, secrets); + } + + private sanitizeResponse(raw: Record, requestPayload?: unknown): Record { + const masked = redactSecrets(raw); + return replaceSecretValuesDeep(masked, this.secretValues(requestPayload)) as Record; + } + + private serializeForLog(value: unknown, requestPayload?: unknown): string { + return this.redactText(JSON.stringify(redactSecrets(value)), requestPayload); + } + + private assertOk(raw: Record, action: string, requestPayload?: unknown): Record { + try { + return assertOk(raw, action); + } catch (error) { + throw new Error(this.redactText((error as Error).message, requestPayload)); + } + } + + private logRequest(method: string, url: string, payload: unknown): void { + const summary = payload && typeof payload === 'object' && !Array.isArray(payload) + ? summarizePayload(payload as Record) + : payload; + this.logger.log(`→ ${method} ${url} 发送摘要=${this.serializeForLog(summary, payload).slice(0, 1000)}`); + } + + private logResponse(method: string, url: string, status: number, text: string, requestPayload?: unknown): void { + const response = parseJson(text); + this.logger.log(`← ${method} ${url} HTTP ${status} 返回=${this.serializeForLog(response, requestPayload).slice(0, 500)}`); } private baseUrl(): string { @@ -114,16 +224,35 @@ export class TianheProvider implements AttestationProvider { private async postJson(path: string, body: Record, action: string): Promise> { const url = `${this.baseUrl()}${path}`; - this.logRequest('POST', url, redactSecrets(body)); - const res = await fetch(url, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body), - }); - const text = await res.text(); - this.logResponse('POST', url, res.status, text); - if (!res.ok) throw new Error(`${action}请求失败:HTTP ${res.status} ${text.slice(0, 200)}`); - return parseJson(text); + this.logRequest('POST', url, body); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); + try { + const res = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + signal: controller.signal, + }); + const text = await res.text(); + this.logResponse('POST', url, res.status, text, body); + if (!res.ok) { + throw new BlockchainSubmissionError( + `${action}请求失败:HTTP ${res.status} ${this.redactText(text, body).slice(0, 200)}`, + isUncertainHttpStatus(res.status), + ); + } + return parseJson(text); + } catch (error) { + if (error instanceof BlockchainSubmissionError) throw error; + const timedOut = controller.signal.aborted; + throw new BlockchainSubmissionError( + `${action}请求${timedOut ? '超时' : '中断'}:${this.redactText((error as Error).message, body)}`, + true, + ); + } finally { + clearTimeout(timer); + } } // 天河链 upload 要求 userDto 分段「无 filename + Content-Type: application/json」(等价 curl 的 ;type=application/json)。 @@ -157,8 +286,10 @@ export class TianheProvider implements AttestationProvider { body, }); const text = await res.text(); - this.logResponse('POST(multipart)', url, res.status, text); - if (!res.ok) throw new Error(`${action}请求失败:HTTP ${res.status} ${text.slice(0, 200)}`); + this.logResponse('POST(multipart)', url, res.status, text, parseJson(userDtoJson)); + if (!res.ok) { + throw new Error(`${action}请求失败:HTTP ${res.status} ${this.redactText(text).slice(0, 200)}`); + } return parseJson(text); } @@ -181,16 +312,17 @@ export class TianheProvider implements AttestationProvider { res.on('data', (chunk) => (text += chunk)); res.on('end', () => { const status = res.statusCode || 0; - this.logResponse('GET(body)', url.toString(), status, text); + this.logResponse('GET(body)', url.toString(), status, text, body); if (status < 200 || status >= 300) { - reject(new Error(`${action}请求失败:HTTP ${status} ${text.slice(0, 200)}`)); + reject(new Error(`${action}请求失败:HTTP ${status} ${this.redactText(text, body).slice(0, 200)}`)); return; } resolve(parseJson(text)); }); }, ); - req.on('error', (e) => reject(new Error(`${action}请求失败:${e.message}`))); + req.on('error', (e) => reject(new Error(`${action}请求失败:${this.redactText(e.message, body)}`))); + req.setTimeout?.(REQUEST_TIMEOUT_MS, () => req.destroy(new Error(`${action}请求超时`))); req.write(payload); req.end(); }); @@ -199,7 +331,7 @@ export class TianheProvider implements AttestationProvider { // 接口 1「用户链上身份注册」:注册托管钱包,返回链上地址。userKey 是钱包密码,天河链不留存。 async registerUser(): Promise<{ address: string }> { const raw = await this.postJson('/api/v2/user', this.credentials(), '天河链链上身份注册'); - const data = assertOk(raw, '天河链链上身份注册'); + const data = this.assertOk(raw, '天河链链上身份注册'); const pubKey = (data.pubKey && typeof data.pubKey === 'object' ? data.pubKey : data) as Record; const address = pickString(pubKey, ['address']) || pickString(data, ['address']); if (!address) throw new Error('天河链链上身份注册失败:响应缺少钱包地址'); @@ -209,7 +341,7 @@ export class TianheProvider implements AttestationProvider { // 接口 8「用户链上身份查询」:校验 userId/userKey 是否对应已注册钱包,返回其地址。 async userInfo(): Promise<{ address: string }> { const raw = await this.postJson('/api/v2/user/info', this.credentials(), '天河链链上身份查询'); - const data = assertOk(raw, '天河链链上身份查询'); + const data = this.assertOk(raw, '天河链链上身份查询'); const address = pickString(data, ['address']); if (!address) throw new Error('天河链链上身份查询失败:响应缺少钱包地址'); return { address }; @@ -244,7 +376,7 @@ export class TianheProvider implements AttestationProvider { }, '天河链存证', ); - const data = assertOk(raw, '天河链存证'); + const data = this.assertOk(raw, '天河链存证'); // 严格要求返回交易哈希;缺失即视为失败(绝不能用本地 dataHash 冒充链上哈希造成「假上链」) const txHash = pickString(data, ['transactionHash', 'txHash']); @@ -265,7 +397,7 @@ export class TianheProvider implements AttestationProvider { onchainAt: new Date(), raw: { requestMeta: meta, - response: raw, + response: this.sanitizeResponse(raw), digest, proofUrl, transactionStatus: 'onchain', @@ -289,11 +421,43 @@ export class TianheProvider implements AttestationProvider { baseTokenId?: number; operateId?: string; }): Promise<{ contractAddress: string; tokenId: number; txHash: string; raw: Record }> { - const body: Record = { - ...this.credentials(), + const result = await this.publishBatch({ productIds: [params.productId], + name: params.name, + author: params.author, + feature: params.feature, + contractAddress: params.contractAddress, + baseTokenId: params.baseTokenId, + operateId: params.operateId || `single-${Date.now()}`, + }); + const product = result.products[0]; + if (!product) throw new BlockchainSubmissionError('天河链数字商品发行失败:响应缺少产品结果', true); + return { + contractAddress: result.contractAddress!, + tokenId: product.tokenId ?? -1, + txHash: product.txHash, + raw: result.raw, + }; + } + + async publishBatch(params: BatchPublishRequest): Promise { + if (!params.productIds.length || params.productIds.length > MAX_PUBLISH_PRODUCTS) { + throw new BlockchainSubmissionError(`单次发行数量必须在 1-${MAX_PUBLISH_PRODUCTS} 之间`, false); + } + if (new Set(params.productIds).size !== params.productIds.length) { + throw new BlockchainSubmissionError('单次发行请求包含重复 productId', false); + } + let credentials: ReturnType; + try { + credentials = this.credentials(); + } catch (error) { + throw new BlockchainSubmissionError((error as Error).message, false); + } + const body: Record = { + ...credentials, + productIds: params.productIds, name: params.name.slice(0, 42), - pieceCount: 1, + pieceCount: params.productIds.length, }; if (params.author) body.author = params.author.slice(0, 120); if (params.feature) body.feature = params.feature.slice(0, 500); @@ -303,27 +467,53 @@ export class TianheProvider implements AttestationProvider { } if (params.operateId) body.operateId = params.operateId.slice(0, 20); - const raw = await this.postJson('/api/v2/nfr/publish', body, '天河链数字商品发行'); - const data = assertOk(raw, '天河链数字商品发行'); + let raw: Record; + let data: Record; + try { + raw = await this.postJson('/api/v2/nfr/publish', body, '天河链数字商品发行'); + data = this.assertOk(raw, '天河链数字商品发行', body); + } catch (error) { + if (error instanceof BlockchainSubmissionError) throw error; + // 已收到 HTTP 200 但业务响应无法解析/确认时,不能假设远端没有受理发行。 + throw new BlockchainSubmissionError((error as Error).message, true); + } const contractAddress = pickString(data, ['contractAddress']); const products = Array.isArray(data.products) ? (data.products as Array>) : []; - const product = products[0]; - const txHash = product ? pickString(product, ['transactionHash', 'txHash']) : null; - const tokenId = product ? pickNumber(product, ['tokenId']) : null; - if (!contractAddress || !txHash) { - throw new Error('天河链数字商品发行失败:响应缺少 contractAddress 或 transactionHash'); + const mapped = products.map((product) => { + const txHash = pickString(product, ['transactionHash', 'txHash']) || ''; + const tokenId = pickNumber(product, ['tokenId']); + return { + productId: pickString(product, ['productId']) || '', + txHash, + tokenId: tokenId !== null && tokenId >= 0 ? tokenId : null, + explorerUrl: this.explorerTxUrl(txHash), + }; + }); + const byProductId = new Map(mapped.map((product) => [product.productId, product])); + const complete = params.productIds.every((id) => { + const product = byProductId.get(id); + return Boolean(product?.txHash); + }); + if (!contractAddress || !complete || mapped.length !== params.productIds.length) { + throw new BlockchainSubmissionError( + '天河链数字商品发行响应不完整,无法确定全部 productId 的交易结果', + true, + ); } - return { contractAddress, tokenId: tokenId ?? -1, txHash, raw }; + return { + contractAddress, + products: params.productIds.map((id) => byProductId.get(id)!), + chainName: '天河链', + confirmationRequired: true, + raw: this.sanitizeResponse(raw, body), + }; } // 接口 7「用户链上身份秘钥修改」:轮换托管钱包 userKey(旧 key 立即失效,调用方须持久化新 key)。 async updateUserKey(newUserKey: string): Promise { - const raw = await this.postJson( - '/api/v2/user/update', - { ...this.credentials(), newUserKey: required(newUserKey, 'New User Key') }, - '天河链秘钥修改', - ); - assertOk(raw, '天河链秘钥修改'); + const body = { ...this.credentials(), newUserKey: required(newUserKey, 'New User Key') }; + const raw = await this.postJson('/api/v2/user/update', body, '天河链秘钥修改'); + this.assertOk(raw, '天河链秘钥修改', body); } // 接口 9「根据交易哈希查询」:确认交易是否已进块。 @@ -338,7 +528,7 @@ export class TianheProvider implements AttestationProvider { }, '天河链交易确认', ); - const data = assertOk(raw, '天河链交易确认'); + const data = this.assertOk(raw, '天河链交易确认'); const status = pickString(data, ['status']); const blockHash = pickString(data, ['blockHash']); @@ -349,11 +539,13 @@ export class TianheProvider implements AttestationProvider { const confirmed = statusOk && Boolean(blockHash || blockHeight !== null); return { confirmed, + failed: Boolean(status && !statusOk), + failureReason: status && !statusOk ? `链上交易执行失败(status=${status})` : undefined, txHash: pickString(data, ['transactionHash', 'txHash']) || txHash, blockHash, blockHeight, raw: { - response: raw, + response: this.sanitizeResponse(raw), transactionStatus: confirmed ? 'confirmed' : statusOk ? 'waiting' : 'failed', tokenId: pickString(data, ['tokenId']), status, diff --git a/apps/api/src/certificate/certificate.controller.ts b/apps/api/src/certificate/certificate.controller.ts index 63c3a7d..9e2aaa9 100644 --- a/apps/api/src/certificate/certificate.controller.ts +++ b/apps/api/src/certificate/certificate.controller.ts @@ -1,9 +1,6 @@ -import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put } from '@nestjs/common'; +import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common'; import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; -import { RoleType } from '@artveris/shared'; import { CertificateService } from './certificate.service'; -import { CreateCertificateDto, UpdateCertificateDto } from './dto/certificate.dto'; -import { Roles } from '../common/decorators/roles.decorator'; @ApiTags('认证文件') @ApiBearerAuth() @@ -16,25 +13,4 @@ export class CertificateController { list(@Param('artworkId', ParseIntPipe) artworkId: number) { return this.certService.listByArtwork(artworkId); } - - @Post('artworks/:artworkId/certificates') - @Roles(RoleType.OPERATOR) - @ApiOperation({ summary: '新增认证文件(自动生成水印图)' }) - create(@Param('artworkId', ParseIntPipe) artworkId: number, @Body() dto: CreateCertificateDto) { - return this.certService.create(artworkId, dto); - } - - @Put('certificates/:id') - @Roles(RoleType.OPERATOR) - @ApiOperation({ summary: '更新认证文件' }) - update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateCertificateDto) { - return this.certService.update(id, dto); - } - - @Delete('certificates/:id') - @Roles(RoleType.OPERATOR) - @ApiOperation({ summary: '删除认证文件' }) - remove(@Param('id', ParseIntPipe) id: number) { - return this.certService.remove(id); - } } diff --git a/apps/api/src/certificate/certificate.module.ts b/apps/api/src/certificate/certificate.module.ts index 0d59846..540bbc5 100644 --- a/apps/api/src/certificate/certificate.module.ts +++ b/apps/api/src/certificate/certificate.module.ts @@ -9,6 +9,5 @@ import { WatermarkProcessor } from './watermark.processor'; imports: [BullModule.registerQueue({ name: QUEUE_NAMES.WATERMARK })], controllers: [CertificateController], providers: [CertificateService, WatermarkProcessor], - exports: [CertificateService], }) export class CertificateModule {} diff --git a/apps/api/src/certificate/certificate.service.ts b/apps/api/src/certificate/certificate.service.ts index a7710fc..7b6729e 100644 --- a/apps/api/src/certificate/certificate.service.ts +++ b/apps/api/src/certificate/certificate.service.ts @@ -1,18 +1,12 @@ import { Injectable } from '@nestjs/common'; -import { InjectQueue } from '@nestjs/bullmq'; -import { Queue } from 'bullmq'; -import { ErrorCode, QUEUE_NAMES } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; import { StorageService } from '../storage/storage.service'; -import { BusinessException } from '../common/exceptions/business.exception'; -import { CreateCertificateDto, UpdateCertificateDto } from './dto/certificate.dto'; @Injectable() export class CertificateService { constructor( private readonly prisma: PrismaService, private readonly storage: StorageService, - @InjectQueue(QUEUE_NAMES.WATERMARK) private readonly watermarkQueue: Queue, ) {} private withUrls(c: T) { @@ -23,11 +17,6 @@ export class CertificateService { }; } - private async ensureArtwork(artworkId: number) { - const a = await this.prisma.artwork.findFirst({ where: { id: artworkId, deletedAt: null } }); - if (!a) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404); - } - async listByArtwork(artworkId: number) { const list = await this.prisma.certificate.findMany({ where: { artworkId }, @@ -35,56 +24,4 @@ export class CertificateService { }); return list.map((c) => this.withUrls(c)); } - - async create(artworkId: number, dto: CreateCertificateDto) { - await this.ensureArtwork(artworkId); - const cert = await this.prisma.certificate.create({ - data: { - artworkId, - name: dto.name, - issuer: dto.issuer, - issuedAt: dto.issuedAt ? new Date(dto.issuedAt) : null, - type: dto.type, - originFileUrl: dto.originKey, - }, - }); - await this.enqueueWatermark(cert.id, dto.originKey); - return this.withUrls(cert); - } - - async update(id: number, dto: UpdateCertificateDto) { - await this.ensureCert(id); - const updated = await this.prisma.certificate.update({ - where: { id }, - data: { - name: dto.name, - issuer: dto.issuer, - issuedAt: dto.issuedAt ? new Date(dto.issuedAt) : undefined, - type: dto.type, - originFileUrl: dto.originKey ?? undefined, - // 重新上传原件则清空水印,等待重做 - watermarkFileUrl: dto.originKey ? null : undefined, - }, - }); - if (dto.originKey) { - await this.enqueueWatermark(id, dto.originKey); - } - return this.withUrls(updated); - } - - async remove(id: number) { - await this.ensureCert(id); - await this.prisma.certificate.delete({ where: { id } }); - return { success: true }; - } - - private async enqueueWatermark(certificateId: number, originKey: string) { - await this.watermarkQueue.add('generate', { certificateId, originKey }); - } - - private async ensureCert(id: number) { - const c = await this.prisma.certificate.findUnique({ where: { id } }); - if (!c) throw new BusinessException(ErrorCode.CERTIFICATE_NOT_FOUND, '认证文件不存在', 404); - return c; - } } diff --git a/apps/api/src/certificate/dto/certificate.dto.ts b/apps/api/src/certificate/dto/certificate.dto.ts deleted file mode 100644 index e9d01a5..0000000 --- a/apps/api/src/certificate/dto/certificate.dto.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; -import { IsDateString, IsEnum, IsNotEmpty, IsOptional, IsString, MaxLength } from 'class-validator'; -import { CertType } from '@artveris/shared'; - -export class CreateCertificateDto { - @ApiProperty({ description: '证书名称' }) - @IsString() - @IsNotEmpty() - @MaxLength(120) - name!: string; - - @ApiPropertyOptional({ description: '颁发机构' }) - @IsOptional() - @IsString() - @MaxLength(120) - issuer?: string; - - @ApiPropertyOptional({ description: '颁发时间' }) - @IsOptional() - @IsDateString() - issuedAt?: string; - - @ApiProperty({ description: '类型', enum: CertType }) - @IsEnum(CertType) - type!: CertType; - - @ApiProperty({ description: '原始文件存储 key(上传接口返回)' }) - @IsString() - @IsNotEmpty() - originKey!: string; -} - -export class UpdateCertificateDto { - @ApiPropertyOptional({ description: '证书名称' }) - @IsOptional() - @IsString() - @MaxLength(120) - name?: string; - - @ApiPropertyOptional({ description: '颁发机构' }) - @IsOptional() - @IsString() - @MaxLength(120) - issuer?: string; - - @ApiPropertyOptional({ description: '颁发时间' }) - @IsOptional() - @IsDateString() - issuedAt?: string; - - @ApiPropertyOptional({ description: '类型', enum: CertType }) - @IsOptional() - @IsEnum(CertType) - type?: CertType; - - @ApiPropertyOptional({ description: '重新上传的原始文件 key(提供则重做水印)' }) - @IsOptional() - @IsString() - originKey?: string; -} diff --git a/apps/api/src/common/dto/trace-code-selection.dto.spec.ts b/apps/api/src/common/dto/trace-code-selection.dto.spec.ts new file mode 100644 index 0000000..f3b380e --- /dev/null +++ b/apps/api/src/common/dto/trace-code-selection.dto.spec.ts @@ -0,0 +1,35 @@ +import { plainToInstance } from 'class-transformer'; +import { TraceCodeFilterDto } from './trace-code-selection.dto'; +import { QueryTraceCodeDto } from '../../trace-code/dto/trace-code.dto'; +import { buildTraceCodeFilterWhere, buildTraceCodeSelectionWhere } from '../utils/trace-code-selection.util'; + +describe('activated query transformation', () => { + it.each([ + [TraceCodeFilterDto, {}], + [QueryTraceCodeDto, {}], + ])('does not turn an omitted activated filter into false', (Dto, input) => { + const dto = plainToInstance(Dto, input); + expect(dto.activated).toBeUndefined(); + expect(buildTraceCodeFilterWhere(dto)).not.toHaveProperty('firstActivatedAt'); + }); + + it.each([ + ['true', true], + ['false', false], + [true, true], + [false, false], + ])('parses %p as %p', (input, expected) => { + expect(plainToInstance(TraceCodeFilterDto, { activated: input }).activated).toBe(expected); + expect(plainToInstance(QueryTraceCodeDto, { activated: input }).activated).toBe(expected); + }); +}); + +describe('large filter exclusions', () => { + it('returns exclusions separately instead of building one unbounded NOT IN query', () => { + const excludeIds = Array.from({ length: 70_000 }, (_, index) => String(index + 1)); + const result = buildTraceCodeSelectionWhere({ mode: 'FILTER', filters: {}, excludeIds }); + + expect(result.excludedIds).toHaveLength(70_000); + expect(JSON.stringify(result.where)).not.toContain('notIn'); + }); +}); diff --git a/apps/api/src/common/dto/trace-code-selection.dto.ts b/apps/api/src/common/dto/trace-code-selection.dto.ts new file mode 100644 index 0000000..8034c87 --- /dev/null +++ b/apps/api/src/common/dto/trace-code-selection.dto.ts @@ -0,0 +1,107 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { Transform, Type } from 'class-transformer'; +import { + ArrayMaxSize, + IsArray, + IsEnum, + IsIn, + IsInt, + IsOptional, + IsString, + Matches, + IsBoolean, + MaxLength, + ValidateIf, + ValidateNested, +} from 'class-validator'; +import { MAX_BATCH_SELECTION, ProofStatus, TraceCodeStatus } from '@artveris/shared'; + +export const ONCHAIN_FILTER_STATUSES = ['ELIGIBLE', 'NONE', ...Object.values(ProofStatus)] as const; +export type OnchainFilterStatus = (typeof ONCHAIN_FILTER_STATUSES)[number]; + +export class TraceCodeFilterDto { + @ApiPropertyOptional({ description: '作品 ID' }) + @IsOptional() + @Type(() => Number) + @IsInt() + artworkId?: number; + + @ApiPropertyOptional({ description: '批次 ID' }) + @IsOptional() + @Type(() => Number) + @IsInt() + batchId?: number; + + @ApiPropertyOptional({ description: '分组 ID' }) + @IsOptional() + @Type(() => Number) + @IsInt() + groupId?: number; + + @ApiPropertyOptional({ enum: TraceCodeStatus }) + @IsOptional() + @IsEnum(TraceCodeStatus) + status?: TraceCodeStatus; + + @ApiPropertyOptional({ enum: ['OUTBOUND', 'NOT_OUTBOUND'] }) + @IsOptional() + @IsIn(['OUTBOUND', 'NOT_OUTBOUND']) + outboundStatus?: 'OUTBOUND' | 'NOT_OUTBOUND'; + + @ApiPropertyOptional({ enum: ONCHAIN_FILTER_STATUSES }) + @IsOptional() + @IsIn(ONCHAIN_FILTER_STATUSES) + proofStatus?: OnchainFilterStatus; + + @ApiPropertyOptional({ description: '是否已经首次激活' }) + @IsOptional() + @Transform(({ value }) => + value === undefined || value === null || value === '' ? undefined : value === true || value === 'true', + ) + @IsBoolean() + activated?: boolean; + + @ApiPropertyOptional({ description: '追溯码、档案号、作品、批次或分组关键词' }) + @IsOptional() + @IsString() + @MaxLength(191) + keyword?: string; +} + +export class TraceCodeSelectionDto { + @ApiProperty({ enum: ['IDS', 'FILTER'] }) + @IsIn(['IDS', 'FILTER']) + mode!: 'IDS' | 'FILTER'; + + @ApiPropertyOptional({ type: [String], description: 'mode=IDS 时的追溯码 ID' }) + @ValidateIf((dto: TraceCodeSelectionDto) => dto.mode === 'IDS') + @IsArray() + @IsString({ each: true }) + @Matches(/^\d+$/, { each: true }) + ids?: string[]; + + @ApiPropertyOptional({ type: TraceCodeFilterDto, description: 'mode=FILTER 时的筛选条件' }) + @ValidateIf((dto: TraceCodeSelectionDto) => dto.mode === 'FILTER') + @ValidateNested() + @Type(() => TraceCodeFilterDto) + filters?: TraceCodeFilterDto; + + @ApiPropertyOptional({ type: [String], description: '筛选全选时排除的追溯码 ID' }) + @IsOptional() + @IsArray() + @IsString({ each: true }) + @Matches(/^\d+$/, { each: true }) + excludeIds?: string[]; +} + +export class MatchTraceCodesDto { + @ApiProperty({ type: [String], description: '12 位追溯码,最多 10000 个' }) + @IsArray() + @ArrayMaxSize(MAX_BATCH_SELECTION) + @IsString({ each: true }) + codes!: string[]; + + @ApiProperty({ enum: ['ONCHAIN', 'OUTBOUND'] }) + @IsIn(['ONCHAIN', 'OUTBOUND']) + operation!: 'ONCHAIN' | 'OUTBOUND'; +} diff --git a/apps/api/src/common/utils/trace-code-selection.util.ts b/apps/api/src/common/utils/trace-code-selection.util.ts new file mode 100644 index 0000000..802c82f --- /dev/null +++ b/apps/api/src/common/utils/trace-code-selection.util.ts @@ -0,0 +1,68 @@ +import { ArtworkStatus, AuditStatus, Prisma, ProofStatus, TraceCodeStatus } from '@prisma/client'; +import { ErrorCode } from '@artveris/shared'; +import { TraceCodeFilterDto, TraceCodeSelectionDto } from '../dto/trace-code-selection.dto'; +import { BusinessException } from '../exceptions/business.exception'; +import { parseBigId } from './bigint.util'; + +export function buildTraceCodeFilterWhere(filter: TraceCodeFilterDto = {}): Prisma.TraceCodeWhereInput { + const where: Prisma.TraceCodeWhereInput = {}; + const and: Prisma.TraceCodeWhereInput[] = []; + if (filter.artworkId) where.artworkId = filter.artworkId; + if (filter.batchId) where.batchId = filter.batchId; + if (filter.groupId) where.groupId = filter.groupId; + if (filter.status) where.status = filter.status; + if (filter.outboundStatus === 'OUTBOUND') where.outbound = { isNot: null }; + if (filter.outboundStatus === 'NOT_OUTBOUND') where.outbound = { is: null }; + if (filter.activated === true) where.firstActivatedAt = { not: null }; + if (filter.activated === false) where.firstActivatedAt = null; + if (filter.proofStatus === 'NONE') where.proofs = { none: {} }; + else if (filter.proofStatus === 'ELIGIBLE') { + where.status = { in: [TraceCodeStatus.INACTIVE, TraceCodeStatus.ACTIVE] }; + where.artwork = { + is: { + deletedAt: null, + status: ArtworkStatus.ACTIVE, + auditStatus: AuditStatus.APPROVED, + images: { not: Prisma.DbNull }, + }, + }; + and.push({ OR: [{ proofs: { none: {} } }, { proofs: { some: { status: ProofStatus.FAILED } } }] }); + } else if (filter.proofStatus) where.proofs = { some: { status: filter.proofStatus as ProofStatus } }; + + const keyword = filter.keyword?.trim(); + if (keyword) { + and.push({ + OR: [ + { shortCode: { contains: keyword } }, + { outbound: { is: { remark: { contains: keyword } } } }, + { artwork: { archiveNo: { contains: keyword } } }, + { artwork: { title: { contains: keyword } } }, + { artwork: { artist: { contains: keyword } } }, + { batch: { batchNo: { contains: keyword } } }, + { group: { name: { contains: keyword } } }, + ], + }); + } + if (and.length) where.AND = and; + return where; +} + +function parseIds(ids: string[] | undefined): bigint[] { + return [...new Set(ids ?? [])].map((id) => parseBigId(id, '追溯码 ID')); +} + +export function buildTraceCodeSelectionWhere(selection: TraceCodeSelectionDto): { + where: Prisma.TraceCodeWhereInput; + orderedIds: bigint[] | null; + excludedIds: bigint[]; +} { + if (selection.mode === 'IDS') { + const ids = parseIds(selection.ids); + if (!ids.length) throw new BusinessException(ErrorCode.BAD_REQUEST, '请至少选择一个追溯码'); + return { where: { id: { in: ids } }, orderedIds: ids, excludedIds: [] }; + } + + const excludedIds = parseIds(selection.excludeIds); + const where = buildTraceCodeFilterWhere(selection.filters ?? {}); + return { where, orderedIds: null, excludedIds }; +} diff --git a/apps/api/src/install/install.service.ts b/apps/api/src/install/install.service.ts index e8cf689..ba4deeb 100644 --- a/apps/api/src/install/install.service.ts +++ b/apps/api/src/install/install.service.ts @@ -43,15 +43,14 @@ export class InstallService { if (!isInstallMode()) { return { installed: true, restartRequired: false }; } - const traceCodeSalt = randomBytes(32).toString('hex'); const settingsEncryptionKey = randomBytes(32).toString('hex'); const databaseUrl = this.buildMysqlUrl(dto); await this.ensureDatabase(dto); await this.assertMysql(databaseUrl); await this.assertRedis(dto); this.runPrismaMigrate(databaseUrl); - await this.seedInstallData(databaseUrl, dto, traceCodeSalt, settingsEncryptionKey); - this.writeEnvFile(dto, databaseUrl, traceCodeSalt, settingsEncryptionKey); + await this.seedInstallData(databaseUrl, dto, settingsEncryptionKey); + this.writeEnvFile(dto, databaseUrl, settingsEncryptionKey); // 本地安装向导调试(ARTVERIS_INSTALL_MODE=1)不主动退出,避免响应未返回连接被掐断; // 生产环境由 PM2/Docker restart policy 重启以加载新 .env。 if (process.env.ARTVERIS_INSTALL_MODE !== '1') { @@ -238,7 +237,6 @@ export class InstallService { private writeEnvFile( dto: InstallRequestDto, databaseUrl: string, - traceCodeSalt: string, settingsEncryptionKey: string, ): void { const baseUrl = dto.baseUrl.replace(/\/$/, ''); @@ -276,9 +274,6 @@ export class InstallService { `JWT_EXPIRES_IN=${q(dto.jwtExpiresIn || '7d')}`, '# 设置项加密密钥(加密 OSS/天河链等密钥);更改会导致已加密数据无法解密', `SETTING_ENCRYPTION_KEY=${q(settingsEncryptionKey)}`, - '# 溯源码盐(决定 12 位码生成),勿更改', - `TRACE_CODE_SALT=${q(traceCodeSalt)}`, - '', '# ===== 文件存储:local | oss =====', `STORAGE_DRIVER=${q(dto.storage.driver)}`, `STORAGE_LOCAL_DIR=${q(localDir)}`, @@ -327,7 +322,7 @@ export class InstallService { return found; } - private async seedInstallData(databaseUrl: string, dto: InstallRequestDto, traceCodeSalt: string, settingsEncryptionKey: string): Promise { + private async seedInstallData(databaseUrl: string, dto: InstallRequestDto, settingsEncryptionKey: string): Promise { const prisma = new PrismaClient({ datasources: { db: { url: databaseUrl } } }); try { await prisma.$connect(); @@ -338,10 +333,14 @@ export class InstallService { update: { passwordHash, realName, role: RoleType.SUPER_ADMIN, status: UserStatus.ACTIVE }, create: { username: dto.admin.username, passwordHash, realName, role: RoleType.SUPER_ADMIN, status: UserStatus.ACTIVE }, }); + await prisma.traceCodeSequence.upsert({ + where: { id: 1 }, + update: {}, + create: { id: 1, nextSeq: 1 }, + }); const settings: Record = { appName: dto.appName, clientBaseUrl: `${dto.baseUrl.replace(/\/$/, '')}/trace`, - traceCodeSalt, settingsEncryptionKey, backupEnabled: String(Boolean(dto.backupEnabled)), storageDriver: dto.storage.driver, diff --git a/apps/api/src/jobs/jobs.controller.ts b/apps/api/src/jobs/jobs.controller.ts index 754e6aa..f70061b 100644 --- a/apps/api/src/jobs/jobs.controller.ts +++ b/apps/api/src/jobs/jobs.controller.ts @@ -1,9 +1,31 @@ import { Controller, Get, Param, Query } from '@nestjs/common'; +import { Type } from 'class-transformer'; +import { IsEnum, IsInt, IsOptional, Max, Min } from 'class-validator'; +import { JobItemStatus } from '@artveris/shared'; import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; import { JobsService } from './jobs.service'; import { QueryJobDto } from './dto/query-job.dto'; import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator'; +class QueryJobItemsDto { + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + page = 1; + + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + @Max(100) + pageSize = 20; + + @IsOptional() + @IsEnum(JobItemStatus) + status?: JobItemStatus; +} + @ApiTags('异步任务') @ApiBearerAuth() @Controller('jobs') @@ -21,4 +43,10 @@ export class JobsController { get(@Param('id') id: string, @CurrentUser() user: AuthUser) { return this.jobsService.get(id, user); } + + @Get(':id/items') + @ApiOperation({ summary: '分页查询任务逐项结果' }) + items(@Param('id') id: string, @Query() query: QueryJobItemsDto, @CurrentUser() user: AuthUser) { + return this.jobsService.items(id, query, user); + } } diff --git a/apps/api/src/jobs/jobs.service.spec.ts b/apps/api/src/jobs/jobs.service.spec.ts index 91da47c..1c5eb34 100644 --- a/apps/api/src/jobs/jobs.service.spec.ts +++ b/apps/api/src/jobs/jobs.service.spec.ts @@ -1,4 +1,5 @@ import { JobsService } from './jobs.service'; +import { JobItemStatus, RoleType } from '@artveris/shared'; describe('JobsService.start', () => { it('rejects a missing or terminal job instead of continuing its worker', async () => { @@ -10,3 +11,46 @@ describe('JobsService.start', () => { await expect(service.start('job-1')).rejects.toThrow('任务不存在或已结束'); }); }); + +describe('JobsService item results', () => { + it('returns the skipped count with job progress', async () => { + const prisma = { + job: { findUnique: jest.fn().mockResolvedValue({ id: 'job-1', createdBy: 7 }) }, + jobItem: { count: jest.fn().mockResolvedValue(3) }, + }; + const service = new JobsService(prisma as any); + + await expect(service.get('job-1', { id: 7, role: RoleType.OPERATOR } as any)).resolves.toMatchObject({ + id: 'job-1', + skippedCount: 3, + }); + expect(prisma.jobItem.count).toHaveBeenCalledWith({ + where: { jobId: 'job-1', status: JobItemStatus.SKIPPED }, + }); + }); + + it('paginates and filters item results after checking job ownership', async () => { + const rows = [{ id: 2n, shortCode: '482731000001', status: JobItemStatus.FAILED }]; + const prisma = { + job: { findUnique: jest.fn().mockResolvedValue({ id: 'job-1', createdBy: 7 }) }, + jobItem: { + count: jest.fn().mockResolvedValueOnce(0).mockResolvedValueOnce(1), + findMany: jest.fn().mockResolvedValue(rows), + }, + $transaction: jest.fn().mockImplementation(async (operations: any[]) => Promise.all(operations)), + }; + const service = new JobsService(prisma as any); + + await expect(service.items( + 'job-1', + { page: 2, pageSize: 20, status: JobItemStatus.FAILED }, + { id: 7, role: RoleType.OPERATOR } as any, + )).resolves.toEqual({ list: rows, total: 1, page: 2, pageSize: 20 }); + expect(prisma.jobItem.findMany).toHaveBeenCalledWith({ + where: { jobId: 'job-1', status: JobItemStatus.FAILED }, + orderBy: [{ sequence: 'asc' }, { id: 'asc' }], + skip: 20, + take: 20, + }); + }); +}); diff --git a/apps/api/src/jobs/jobs.service.ts b/apps/api/src/jobs/jobs.service.ts index 7098871..b46d590 100644 --- a/apps/api/src/jobs/jobs.service.ts +++ b/apps/api/src/jobs/jobs.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@nestjs/common'; import { Prisma } from '@prisma/client'; -import { ErrorCode, JobStatus, JobType, RoleType } from '@artveris/shared'; +import { ErrorCode, JobItemStatus, JobStatus, JobType, RoleType } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; import { BusinessException } from '../common/exceptions/business.exception'; import { buildPage } from '../common/utils/pagination.util'; @@ -55,7 +55,32 @@ export class JobsService { if (user && user.role !== RoleType.SUPER_ADMIN && job.createdBy !== user.id) { throw new BusinessException(ErrorCode.FORBIDDEN, '没有访问该任务的权限', 403); } - return job; + const skippedCount = await this.prisma.jobItem.count({ + where: { jobId: id, status: JobItemStatus.SKIPPED }, + }); + return { ...job, skippedCount }; + } + + async items( + id: string, + query: { page: number; pageSize: number; status?: JobItemStatus }, + user?: AuthUser, + ) { + await this.get(id, user); + const where: Prisma.JobItemWhereInput = { + jobId: id, + ...(query.status ? { status: query.status } : {}), + }; + const [items, total] = await this.prisma.$transaction([ + this.prisma.jobItem.findMany({ + where, + orderBy: [{ sequence: 'asc' }, { id: 'asc' }], + skip: (query.page - 1) * query.pageSize, + take: query.pageSize, + }), + this.prisma.jobItem.count({ where }), + ]); + return buildPage(items, total, query.page, query.pageSize); } async list(query: QueryJobDto, user?: AuthUser) { diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 9af643a..c7c5466 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -30,8 +30,11 @@ async function bootstrap(): Promise { const installing = isInstallMode(); const rootModule = installing ? InstallAppModule : (await import('./app.module')).AppModule; const app = await NestFactory.create(rootModule, { - bodyParser: true, + bodyParser: false, }); + // 允许批量粘贴/显式多选的结构化请求;文件上传仍由 Multer 流式落盘处理,不进入 JSON 内存。 + app.useBodyParser('json', { limit: '10mb' }); + app.useBodyParser('urlencoded', { limit: '10mb', extended: true }); const config = app.get(ConfigService); const logger = new Logger('Bootstrap'); diff --git a/apps/api/src/operation-log/operation-log.interceptor.spec.ts b/apps/api/src/operation-log/operation-log.interceptor.spec.ts index 439fc00..a275fc2 100644 --- a/apps/api/src/operation-log/operation-log.interceptor.spec.ts +++ b/apps/api/src/operation-log/operation-log.interceptor.spec.ts @@ -1,4 +1,4 @@ -import { actionOf, moduleOf } from './operation-log.interceptor'; +import { actionOf, moduleOf, sanitize } from './operation-log.interceptor'; describe('operation log route mapping', () => { it('keeps backup create and delete as separate actions', () => { @@ -27,4 +27,43 @@ describe('operation log route mapping', () => { expect(moduleOf('/api/artworks/1/certificates')).toBe('certificates'); expect(moduleOf('/api/artworks/1/nodes')).toBe('nodes'); }); + + it('recursively redacts secrets without depending on key casing', () => { + const secrets = [ + 'password-secret', + 'token-secret', + 'authorization-secret', + 'app-key-secret', + 'user-key-secret', + 'new-user-key-secret', + 'tianhe-app-key-secret', + 'tianhe-user-key-secret', + 'oss-secret', + ]; + const result = sanitize({ + Password: secrets[0], + nested: { + TOKEN: secrets[1], + Authorization: secrets[2], + appKey: secrets[3], + USER_KEY: secrets[4], + newUserKey: secrets[5], + accessKeyId: 'public-access-key-id', + tokenId: 'public-token-id', + children: [ + { + TIANHE_APP_KEY: secrets[6], + tianheUserKey: secrets[7], + OSS_ACCESS_KEY_SECRET: secrets[8], + }, + ], + }, + }); + const serialized = JSON.stringify(result); + + for (const secret of secrets) expect(serialized).not.toContain(secret); + expect(serialized).toContain('public-access-key-id'); + expect(serialized).toContain('public-token-id'); + expect(serialized.match(/\[Redacted\]/g)).toHaveLength(secrets.length); + }); }); diff --git a/apps/api/src/operation-log/operation-log.interceptor.ts b/apps/api/src/operation-log/operation-log.interceptor.ts index 0a54c09..65f3617 100644 --- a/apps/api/src/operation-log/operation-log.interceptor.ts +++ b/apps/api/src/operation-log/operation-log.interceptor.ts @@ -5,16 +5,32 @@ import { catchError, tap } from 'rxjs/operators'; import { AuthUser } from '../common/decorators/current-user.decorator'; import { OperationLogService } from './operation-log.service'; -const SENSITIVE_KEYS = new Set(['password', 'oldPassword', 'newPassword', 'token', 'authorization']); +const SENSITIVE_KEY_SUFFIXES = [ + 'password', + 'token', + 'authorization', + 'appkey', + 'apikey', + 'userkey', + 'secret', + 'secretaccesskey', + 'privatekey', + 'encryptionkey', +]; -function sanitize(value: unknown, depth = 0): unknown { +function isSensitiveKey(key: string): boolean { + const normalized = key.replace(/[^a-z0-9]/gi, '').toLowerCase(); + return SENSITIVE_KEY_SUFFIXES.some((suffix) => normalized.endsWith(suffix)); +} + +export function sanitize(value: unknown, depth = 0): unknown { if (depth > 3) return '[Truncated]'; if (value === null || value === undefined) return value; if (typeof value !== 'object') return value; if (Array.isArray(value)) return value.slice(0, 20).map((item) => sanitize(item, depth + 1)); const out: Record = {}; for (const [key, val] of Object.entries(value as Record)) { - if (SENSITIVE_KEYS.has(key)) { + if (isSensitiveKey(key)) { out[key] = '[Redacted]'; } else if (typeof val === 'string' && val.length > 300) { out[key] = `${val.slice(0, 300)}...`; diff --git a/apps/api/src/outbound/batch-outbound-recovery.service.spec.ts b/apps/api/src/outbound/batch-outbound-recovery.service.spec.ts new file mode 100644 index 0000000..48a5bfc --- /dev/null +++ b/apps/api/src/outbound/batch-outbound-recovery.service.spec.ts @@ -0,0 +1,83 @@ +import { JobItemStatus, JobStatus, JobType } from '@prisma/client'; +import { BatchOutboundRecoveryService } from './batch-outbound-recovery.service'; + +function createHarness(queueJob?: { getState: jest.Mock; retry: jest.Mock; remove: jest.Mock }) { + const pending = { + id: 'job-1', + type: JobType.BATCH_OUTBOUND, + status: JobStatus.PENDING, + payload: { preparing: true }, + }; + const prisma = { + job: { + findMany: jest.fn().mockResolvedValue([pending]), + update: jest.fn().mockResolvedValue({}), + }, + jobItem: { updateMany: jest.fn().mockResolvedValue({ count: 0 }) }, + $transaction: jest.fn().mockImplementation(async (operations: any[]) => Promise.all(operations)), + }; + const queue = { + getJob: jest.fn().mockResolvedValue(queueJob ?? null), + add: jest.fn().mockResolvedValue({}), + }; + const service = new BatchOutboundRecoveryService(prisma as any, queue as any); + return { service, prisma, queue }; +} + +describe('BatchOutboundRecoveryService', () => { + it('immediately re-enqueues a pending preparation with a deterministic Bull job id', async () => { + const harness = createHarness(); + + await harness.service.recoverPending(); + + expect(harness.queue.add).toHaveBeenCalledWith( + 'batch-outbound', + { jobId: 'job-1' }, + { jobId: 'batch-outbound-job-1' }, + ); + }); + + it('retries a failed Bull delivery instead of creating a duplicate', async () => { + const queueJob = { + getState: jest.fn().mockResolvedValue('failed'), + retry: jest.fn().mockResolvedValue(undefined), + remove: jest.fn(), + }; + const harness = createHarness(queueJob); + + await harness.service.recoverPending(); + + expect(queueJob.retry).toHaveBeenCalledTimes(1); + expect(harness.queue.add).not.toHaveBeenCalled(); + }); + + it('resets stale processing items before resuming their job', async () => { + const harness = createHarness(); + harness.prisma.job.findMany.mockResolvedValue([{ + id: 'job-2', + type: JobType.BATCH_OUTBOUND, + status: JobStatus.PROCESSING, + payload: { preparing: false }, + }]); + + await harness.service.recoverPending(); + + expect(harness.prisma.jobItem.updateMany).toHaveBeenCalledWith({ + where: { + jobId: 'job-2', + status: JobItemStatus.PROCESSING, + updatedAt: { lt: expect.any(Date) }, + }, + data: { status: JobItemStatus.PENDING, error: null }, + }); + expect(harness.prisma.job.update).toHaveBeenCalledWith({ + where: { id: 'job-2' }, + data: { status: JobStatus.PENDING }, + }); + expect(harness.queue.add).toHaveBeenCalledWith( + 'batch-outbound', + { jobId: 'job-2' }, + { jobId: 'batch-outbound-job-2' }, + ); + }); +}); diff --git a/apps/api/src/outbound/batch-outbound-recovery.service.ts b/apps/api/src/outbound/batch-outbound-recovery.service.ts new file mode 100644 index 0000000..23793fe --- /dev/null +++ b/apps/api/src/outbound/batch-outbound-recovery.service.ts @@ -0,0 +1,84 @@ +import { InjectQueue } from '@nestjs/bullmq'; +import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; +import { Interval } from '@nestjs/schedule'; +import { JobItemStatus, JobStatus, JobType, Prisma } from '@prisma/client'; +import { Queue } from 'bullmq'; +import { QUEUE_NAMES } from '@artveris/shared'; +import { PrismaService } from '../prisma/prisma.service'; + +const STALE_MS = 5 * 60_000; + +@Injectable() +export class BatchOutboundRecoveryService implements OnModuleInit { + private readonly logger = new Logger(BatchOutboundRecoveryService.name); + private recovering = false; + + constructor( + private readonly prisma: PrismaService, + @InjectQueue(QUEUE_NAMES.BATCH_OUTBOUND) private readonly queue: Queue, + ) {} + + async onModuleInit(): Promise { + await this.recoverPending(); + } + + @Interval(60_000) + async recoverPending(): Promise { + if (this.recovering) return; + this.recovering = true; + try { + const staleBefore = new Date(Date.now() - STALE_MS); + const jobs = await this.prisma.job.findMany({ + where: { + type: JobType.BATCH_OUTBOUND, + OR: [ + { status: JobStatus.PENDING }, + { status: JobStatus.PROCESSING, updatedAt: { lt: staleBefore } }, + ], + }, + orderBy: { createdAt: 'asc' }, + take: 20, + }); + for (const job of jobs) { + const payload = job.payload && typeof job.payload === 'object' && !Array.isArray(job.payload) + ? job.payload as Record + : {}; + if (payload.preparing === true) { + await this.enqueue(job.id); + continue; + } + if (job.status === JobStatus.PROCESSING) { + await this.prisma.$transaction([ + this.prisma.jobItem.updateMany({ + where: { jobId: job.id, status: JobItemStatus.PROCESSING, updatedAt: { lt: staleBefore } }, + data: { status: JobItemStatus.PENDING, error: null }, + }), + this.prisma.job.update({ where: { id: job.id }, data: { status: JobStatus.PENDING } }), + ]); + } + await this.enqueue(job.id); + } + } finally { + this.recovering = false; + } + } + + private async enqueue(jobId: string) { + const bullId = `batch-outbound-${jobId}`; + try { + const existing = await this.queue.getJob(bullId); + if (existing) { + const state = await existing.getState(); + if (state === 'failed') await existing.retry(); + else if (state === 'completed') { + await existing.remove(); + await this.queue.add('batch-outbound', { jobId }, { jobId: bullId }); + } + } else { + await this.queue.add('batch-outbound', { jobId }, { jobId: bullId }); + } + } catch (error) { + this.logger.warn(`恢复批量出库任务失败:${jobId} ${(error as Error).message}`); + } + } +} diff --git a/apps/api/src/outbound/batch-outbound.processor.spec.ts b/apps/api/src/outbound/batch-outbound.processor.spec.ts new file mode 100644 index 0000000..aa6bf14 --- /dev/null +++ b/apps/api/src/outbound/batch-outbound.processor.spec.ts @@ -0,0 +1,211 @@ +import { JobItemStatus, JobStatus, JobType } from '@prisma/client'; +import { BatchOutboundProcessor } from './batch-outbound.processor'; + +function code(id: bigint, outbound = false) { + return { + id, + shortCode: id.toString().padStart(12, '0'), + outbound: outbound ? { id: id + 1000n } : null, + }; +} + +function createHarness(codes: ReturnType[]) { + const items: any[] = []; + const records = new Map(codes.map((item) => [item.id, item])); + const jobRecord: any = { + id: 'job-1', + type: JobType.BATCH_OUTBOUND, + status: JobStatus.PENDING, + total: 0, + successCount: 0, + failCount: 0, + createdBy: 7, + payload: { + selection: { mode: 'IDS', ids: codes.map((item) => item.id.toString()) }, + outTime: '2026-07-15T10:00:00.000Z', + remark: '批量出库', + preparing: true, + }, + }; + const jobItem = { + createMany: jest.fn().mockImplementation(async ({ data }: any) => { + for (const entry of data) { + if (items.some((item) => item.jobId === entry.jobId && item.selectionKey === entry.selectionKey)) continue; + items.push({ id: BigInt(items.length + 1), ...entry, result: entry.result ?? null, error: entry.error ?? null }); + } + return { count: data.length }; + }), + count: jest.fn().mockImplementation(async ({ where }: any) => + items.filter((item) => item.jobId === where.jobId).length, + ), + findMany: jest.fn().mockImplementation(async ({ where, take }: any) => + items + .filter((item) => item.jobId === where.jobId && item.status === where.status) + .sort((a, b) => a.sequence - b.sequence) + .slice(0, take), + ), + updateMany: jest.fn().mockImplementation(async ({ where, data }: any) => { + const item = items.find((entry) => entry.id === where.id && entry.status === where.status); + if (!item) return { count: 0 }; + Object.assign(item, data); + return { count: 1 }; + }), + update: jest.fn().mockImplementation(async ({ where, data }: any) => { + const item = items.find((entry) => entry.id === where.id); + if (!item) throw new Error('item not found'); + Object.assign(item, data); + return item; + }), + groupBy: jest.fn().mockImplementation(async () => { + const counts = new Map(); + for (const item of items) counts.set(item.status, (counts.get(item.status) ?? 0) + 1); + return [...counts].map(([status, count]) => ({ status, _count: { _all: count } })); + }), + }; + const traceCode = { + findMany: jest.fn().mockImplementation(async () => codes), + findUnique: jest.fn().mockImplementation(async ({ where }: any) => records.get(where.id) ?? null), + }; + const outboundRecord = { + create: jest.fn().mockImplementation(async ({ data }: any) => { + const current = records.get(data.traceCodeId)!; + if (current.outbound) throw Object.assign(new Error('duplicate'), { code: 'P2002' }); + const outbound = { id: data.traceCodeId + 2000n }; + current.outbound = outbound; + return outbound; + }), + }; + const prisma = { + job: { + findUnique: jest.fn().mockResolvedValue(jobRecord), + updateMany: jest.fn().mockImplementation(async ({ data }: any) => { + Object.assign(jobRecord, data); + return { count: 1 }; + }), + update: jest.fn().mockImplementation(async ({ data }: any) => { + Object.assign(jobRecord, data); + return jobRecord; + }), + }, + jobItem, + traceCode, + outboundRecord, + $transaction: jest.fn().mockImplementation(async (operation: any) => + typeof operation === 'function' ? operation({ jobItem, traceCode, outboundRecord }) : Promise.all(operation), + ), + }; + const processor = new BatchOutboundProcessor(prisma as any); + jest.spyOn((processor as any).logger, 'log').mockImplementation(() => undefined); + return { processor, prisma, items, jobRecord, records }; +} + +describe('BatchOutboundProcessor', () => { + it('prepares items and records each eligible outbound without being blocked by skipped rows', async () => { + const harness = createHarness([code(1n), code(2n, true), code(3n)]); + + await harness.processor.process({ data: { jobId: 'job-1' } } as any); + + expect(harness.items.map((item) => item.status)).toEqual([ + JobItemStatus.SUCCESS, + JobItemStatus.SKIPPED, + JobItemStatus.SUCCESS, + ]); + expect(harness.prisma.outboundRecord.create).toHaveBeenCalledTimes(2); + expect(harness.jobRecord).toMatchObject({ + total: 3, + status: JobStatus.SUCCESS, + successCount: 2, + failCount: 0, + }); + }); + + it('marks a disappeared trace code failed while allowing the remaining rows to succeed', async () => { + const harness = createHarness([code(1n), code(2n)]); + harness.prisma.traceCode.findUnique.mockImplementation(async ({ where }: any) => + where.id === 1n ? null : harness.records.get(where.id) ?? null, + ); + + await harness.processor.process({ data: { jobId: 'job-1' } } as any); + + expect(harness.items.map((item) => item.status)).toEqual([JobItemStatus.FAILED, JobItemStatus.SUCCESS]); + expect(harness.jobRecord).toMatchObject({ + status: JobStatus.PARTIAL, + successCount: 1, + failCount: 1, + }); + }); + + it('records an ID deleted before preparation as failed and continues the remaining rows', async () => { + const harness = createHarness([code(1n), code(2n)]); + harness.prisma.traceCode.findMany.mockResolvedValue([harness.records.get(2n)]); + + await harness.processor.process({ data: { jobId: 'job-1' } } as any); + + expect(harness.items).toEqual([ + expect.objectContaining({ traceCodeId: null, selectionKey: '1', status: JobItemStatus.FAILED }), + expect.objectContaining({ traceCodeId: 2n, selectionKey: '2', status: JobItemStatus.SUCCESS }), + ]); + expect(harness.jobRecord).toMatchObject({ + status: JobStatus.PARTIAL, + successCount: 1, + failCount: 1, + }); + }); + + it('prepares FILTER selections in stable cursor pages without loading all rows at once', async () => { + const allCodes = Array.from({ length: 1001 }, (_, index) => code(BigInt(index + 1))); + const harness = createHarness(allCodes); + harness.jobRecord.payload.selection = { mode: 'FILTER', filters: {}, excludeIds: [] }; + harness.jobRecord.payload.snapshotMaxId = '1001'; + harness.prisma.traceCode.findMany + .mockResolvedValueOnce(allCodes.slice(0, 1000)) + .mockResolvedValueOnce(allCodes.slice(1000)) + .mockResolvedValueOnce([]); + + await expect((harness.processor as any).prepareItems('job-1', harness.jobRecord.payload)).resolves.toBe(true); + + expect(harness.prisma.traceCode.findMany).toHaveBeenCalledTimes(3); + expect(harness.prisma.jobItem.createMany).toHaveBeenCalledTimes(2); + expect(harness.items).toHaveLength(1001); + expect(harness.items[1000].sequence).toBe(1000); + expect(harness.jobRecord.total).toBe(1001); + }); + + it('keeps codes that became outbound after the FILTER selection cutoff as skipped results', async () => { + const harness = createHarness([code(1n, true)]); + harness.jobRecord.payload.selection = { + mode: 'FILTER', + filters: { outboundStatus: 'NOT_OUTBOUND' }, + excludeIds: [], + }; + harness.jobRecord.payload.selectionCutoff = '2026-07-15T10:00:00.000Z'; + harness.jobRecord.payload.snapshotMaxId = '1'; + harness.prisma.traceCode.findMany + .mockResolvedValueOnce([harness.records.get(1n)]) + .mockResolvedValueOnce([]); + + await expect((harness.processor as any).prepareItems('job-1', harness.jobRecord.payload)).resolves.toBe(true); + + const where = harness.prisma.traceCode.findMany.mock.calls[0][0].where; + expect(JSON.stringify(where, (_key, value) => typeof value === 'bigint' ? value.toString() : value)) + .toContain('2026-07-15T10:00:00.000Z'); + expect(harness.items).toEqual([ + expect.objectContaining({ traceCodeId: 1n, status: JobItemStatus.SKIPPED }), + ]); + }); + + it('chunks explicit ID selections instead of issuing an unbounded IN query', async () => { + const allCodes = Array.from({ length: 1001 }, (_, index) => code(BigInt(index + 1))); + const harness = createHarness(allCodes); + harness.prisma.traceCode.findMany.mockImplementation(async ({ where }: any) => { + const ids = where.id.in as bigint[]; + return ids.map((id) => harness.records.get(id)); + }); + + await expect((harness.processor as any).prepareItems('job-1', harness.jobRecord.payload)).resolves.toBe(true); + + expect(harness.prisma.traceCode.findMany).toHaveBeenCalledTimes(2); + expect(harness.prisma.jobItem.createMany).toHaveBeenCalledTimes(2); + expect(harness.items).toHaveLength(1001); + }); +}); diff --git a/apps/api/src/outbound/batch-outbound.processor.ts b/apps/api/src/outbound/batch-outbound.processor.ts new file mode 100644 index 0000000..8c5aeb0 --- /dev/null +++ b/apps/api/src/outbound/batch-outbound.processor.ts @@ -0,0 +1,295 @@ +import { Processor, WorkerHost } from '@nestjs/bullmq'; +import { Logger } from '@nestjs/common'; +import { Job as BullJob } from 'bullmq'; +import { JobItemStatus, JobStatus, JobType, Prisma } from '@prisma/client'; +import { QUEUE_NAMES } from '@artveris/shared'; +import { PrismaService } from '../prisma/prisma.service'; +import { TraceCodeSelectionDto } from '../common/dto/trace-code-selection.dto'; +import { buildTraceCodeSelectionWhere } from '../common/utils/trace-code-selection.util'; + +interface BatchOutboundJobData { + jobId: string; +} + +@Processor(QUEUE_NAMES.BATCH_OUTBOUND) +export class BatchOutboundProcessor extends WorkerHost { + private readonly logger = new Logger(BatchOutboundProcessor.name); + + constructor(private readonly prisma: PrismaService) { + super(); + } + + async process(job: BullJob): Promise { + const record = await this.prisma.job.findUnique({ where: { id: job.data.jobId } }); + if (!record || record.type !== JobType.BATCH_OUTBOUND) return; + if (record.status === JobStatus.SUCCESS || record.status === JobStatus.PARTIAL || record.status === JobStatus.FAILED) return; + let payload = record.payload && typeof record.payload === 'object' && !Array.isArray(record.payload) + ? record.payload as Record + : {}; + if (payload.preparing === true) { + const prepared = await this.prepareItems(record.id, payload); + if (!prepared) return; + payload = { ...payload, preparing: false }; + } + const outTime = typeof payload.outTime === 'string' ? new Date(payload.outTime) : null; + const remark = typeof payload.remark === 'string' ? payload.remark : null; + if (!outTime || Number.isNaN(outTime.getTime())) { + await this.failRemaining(record.id, '批量出库任务缺少有效出库时间'); + return; + } + await this.prisma.job.updateMany({ + where: { id: record.id, status: { in: [JobStatus.PENDING, JobStatus.PROCESSING] } }, + data: { status: JobStatus.PROCESSING }, + }); + + while (true) { + const items = await this.prisma.jobItem.findMany({ + where: { jobId: record.id, status: JobItemStatus.PENDING }, + orderBy: { sequence: 'asc' }, + take: 100, + }); + if (!items.length) break; + for (const item of items) { + const traceCodeId = item.traceCodeId; + if (traceCodeId === null) { + await this.prisma.jobItem.update({ + where: { id: item.id }, + data: { status: JobItemStatus.FAILED, error: '任务明细关联的追溯码已不存在' }, + }); + continue; + } + const claimed = await this.prisma.jobItem.updateMany({ + where: { id: item.id, status: JobItemStatus.PENDING }, + data: { status: JobItemStatus.PROCESSING, error: null }, + }); + if (claimed.count !== 1) continue; + try { + await this.prisma.$transaction(async (tx) => { + const code = await tx.traceCode.findUnique({ + where: { id: traceCodeId }, + include: { outbound: { select: { id: true } } }, + }); + if (!code) { + await tx.jobItem.update({ + where: { id: item.id }, + data: { status: JobItemStatus.FAILED, error: '追溯码已不存在' }, + }); + return; + } + const existing = code.outbound; + if (existing) { + await tx.jobItem.update({ + where: { id: item.id }, + data: { + status: JobItemStatus.SKIPPED, + result: { reason: '该追溯码已登记出库', outboundRecordId: existing.id.toString() }, + }, + }); + return; + } + const outbound = await tx.outboundRecord.create({ + data: { + traceCodeId, + outTime, + remark, + createdBy: record.createdBy, + updatedBy: record.createdBy, + }, + }); + await tx.jobItem.update({ + where: { id: item.id }, + data: { + status: JobItemStatus.SUCCESS, + result: { outboundRecordId: outbound.id.toString(), outTime: outTime.toISOString() }, + }, + }); + }); + } catch (error) { + if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') { + await this.prisma.jobItem.update({ + where: { id: item.id }, + data: { status: JobItemStatus.SKIPPED, result: { reason: '该追溯码已登记出库' }, error: null }, + }); + } else { + await this.prisma.jobItem.update({ + where: { id: item.id }, + data: { status: JobItemStatus.FAILED, error: (error as Error).message.slice(0, 2000) }, + }); + } + } + } + await this.updateProgress(record.id, false); + } + await this.updateProgress(record.id, true); + } + + private async prepareItems(jobId: string, payload: Record): Promise { + const selection = payload.selection as unknown as TraceCodeSelectionDto; + if (!selection?.mode) { + await this.failRemaining(jobId, '批量出库任务缺少选择条件'); + return false; + } + const { where: selectionWhere, orderedIds, excludedIds } = buildTraceCodeSelectionWhere(selection); + const excluded = new Set(excludedIds); + const selectionCutoff = typeof payload.selectionCutoff === 'string' ? new Date(payload.selectionCutoff) : null; + const outboundStatus = selection.mode === 'FILTER' ? selection.filters?.outboundStatus : undefined; + if (selectionCutoff && !Number.isNaN(selectionCutoff.getTime()) && outboundStatus) { + delete selectionWhere.outbound; + const existingAnd = Array.isArray(selectionWhere.AND) + ? selectionWhere.AND + : selectionWhere.AND + ? [selectionWhere.AND] + : []; + selectionWhere.AND = [ + ...existingAnd, + outboundStatus === 'NOT_OUTBOUND' + ? { + OR: [ + { outbound: { is: null } }, + { outbound: { is: { createdAt: { gt: selectionCutoff } } } }, + ], + } + : { outbound: { is: { createdAt: { lte: selectionCutoff } } } }, + ]; + } + const snapshotMaxId = typeof payload.snapshotMaxId === 'string' ? BigInt(payload.snapshotMaxId) : null; + const where = snapshotMaxId ? { AND: [selectionWhere, { id: { lte: snapshotMaxId } }] } : selectionWhere; + let total = 0; + try { + if (orderedIds) { + for (let offset = 0; offset < orderedIds.length; offset += 1000) { + const chunkIds = orderedIds.slice(offset, offset + 1000); + const codes = await this.prisma.traceCode.findMany({ + where: { id: { in: chunkIds } }, + include: { outbound: { select: { id: true } } }, + }); + const byId = new Map(codes.map((code) => [code.id.toString(), code])); + await this.createSelectedIdItems(jobId, chunkIds, byId, offset); + total += chunkIds.length; + } + } else { + let cursor: bigint | undefined; + while (true) { + const pageCodes = await this.prisma.traceCode.findMany({ + where, + include: { outbound: { select: { id: true } } }, + orderBy: { id: 'asc' }, + take: 1000, + ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}), + }); + if (!pageCodes.length) break; + const codes = pageCodes.filter((code) => !excluded.has(code.id)); + await this.createItems(jobId, codes, total); + total += codes.length; + cursor = pageCodes[pageCodes.length - 1].id; + } + } + total = await this.prisma.jobItem.count({ where: { jobId } }); + if (!total) throw new Error('没有可处理的追溯码'); + await this.prisma.job.update({ + where: { id: jobId }, + data: { total, payload: { ...payload, preparing: false } as Prisma.InputJsonObject }, + }); + return true; + } catch (error) { + await this.failRemaining(jobId, `批量出库任务准备失败:${(error as Error).message}`); + return false; + } + } + + private createItems(jobId: string, codes: Array, offset: number) { + return this.prisma.jobItem.createMany({ + data: codes.map((code, index) => ({ + jobId, + traceCodeId: code.id, + selectionKey: code.id.toString(), + shortCode: code.shortCode, + sequence: offset + index, + status: code.outbound ? JobItemStatus.SKIPPED : JobItemStatus.PENDING, + ...(code.outbound ? { result: { reason: '该追溯码已登记出库' } } : {}), + })), + skipDuplicates: true, + }); + } + + private createSelectedIdItems(jobId: string, ids: bigint[], byId: Map, offset: number) { + return this.prisma.jobItem.createMany({ + data: ids.map((id, index) => { + const code = byId.get(id.toString()); + if (!code) { + return { + jobId, + traceCodeId: null, + selectionKey: id.toString(), + shortCode: `ID:${id.toString()}`, + sequence: offset + index, + status: JobItemStatus.FAILED, + error: '追溯码在任务准备前已不存在', + result: { requestedId: id.toString(), reason: '追溯码在任务准备前已不存在' }, + }; + } + return { + jobId, + traceCodeId: code.id, + selectionKey: code.id.toString(), + shortCode: code.shortCode, + sequence: offset + index, + status: code.outbound ? JobItemStatus.SKIPPED : JobItemStatus.PENDING, + ...(code.outbound ? { result: { reason: '该追溯码已登记出库' } } : {}), + }; + }), + skipDuplicates: true, + }); + } + + private async failRemaining(jobId: string, reason: string) { + await this.prisma.jobItem.updateMany({ + where: { jobId, status: { in: [JobItemStatus.PENDING, JobItemStatus.PROCESSING] } }, + data: { status: JobItemStatus.FAILED, error: reason }, + }); + const [failed, itemTotal, job] = await this.prisma.$transaction([ + this.prisma.jobItem.count({ where: { jobId, status: JobItemStatus.FAILED } }), + this.prisma.jobItem.count({ where: { jobId } }), + this.prisma.job.findUnique({ where: { id: jobId }, select: { total: true } }), + ]); + await this.prisma.job.update({ + where: { id: jobId }, + data: { + status: JobStatus.FAILED, + total: Math.max(job?.total ?? 0, itemTotal), + failCount: failed, + error: reason, + }, + }); + } + + private async updateProgress(jobId: string, terminal: boolean) { + const counts = await this.prisma.jobItem.groupBy({ + by: ['status'], + where: { jobId }, + _count: { _all: true }, + }); + const count = (status: JobItemStatus) => counts.find((row) => row.status === status)?._count._all ?? 0; + const success = count(JobItemStatus.SUCCESS); + const failed = count(JobItemStatus.FAILED) + count(JobItemStatus.UNKNOWN); + const skipped = count(JobItemStatus.SKIPPED); + const remaining = count(JobItemStatus.PENDING) + count(JobItemStatus.PROCESSING); + const status = terminal && remaining === 0 + ? failed === 0 + ? JobStatus.SUCCESS + : success + skipped > 0 + ? JobStatus.PARTIAL + : JobStatus.FAILED + : JobStatus.PROCESSING; + await this.prisma.job.update({ + where: { id: jobId }, + data: { + status, + successCount: success, + failCount: failed, + error: failed ? `${failed} 条出库失败` : null, + }, + }); + if (terminal) this.logger.log(`批量出库完成:job=${jobId} success=${success} failed=${failed} skipped=${skipped}`); + } +} diff --git a/apps/api/src/outbound/dto/outbound.dto.ts b/apps/api/src/outbound/dto/outbound.dto.ts index 2da5957..05f8eb7 100644 --- a/apps/api/src/outbound/dto/outbound.dto.ts +++ b/apps/api/src/outbound/dto/outbound.dto.ts @@ -1,22 +1,22 @@ -import { ApiPropertyOptional } from '@nestjs/swagger'; -import { IsArray, IsDateString, IsOptional, IsString, MaxLength } from 'class-validator'; +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { Type } from 'class-transformer'; +import { + IsDateString, + IsIn, + IsInt, + IsOptional, + IsString, + Max, + MaxLength, + Min, + ValidateNested, +} from 'class-validator'; +import { TraceCodeSelectionDto } from '../../common/dto/trace-code-selection.dto'; export class OutboundDto { - @ApiPropertyOptional({ description: '出库时间' }) - @IsOptional() + @ApiProperty({ description: '出库时间' }) @IsDateString() - outTime?: string | null; - - @ApiPropertyOptional({ description: '出库实况图存储 key' }) - @IsOptional() - @IsString() - outImageKey?: string | null; - - @ApiPropertyOptional({ description: '出库实况图存储 key 列表' }) - @IsOptional() - @IsArray() - @IsString({ each: true }) - outImageKeys?: string[]; + outTime!: string; @ApiPropertyOptional({ description: '备注' }) @IsOptional() @@ -24,3 +24,33 @@ export class OutboundDto { @MaxLength(191) remark?: string | null; } + +export class BatchOutboundDto extends OutboundDto { + @ApiProperty({ type: TraceCodeSelectionDto }) + @ValidateNested() + @Type(() => TraceCodeSelectionDto) + selection!: TraceCodeSelectionDto; +} + +export class QueryOutboundImagesDto { + @ApiPropertyOptional({ default: 1 }) + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + page = 1; + + @ApiPropertyOptional({ default: 20, maximum: 100 }) + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + @Max(100) + pageSize = 20; +} + +export class MoveOutboundImageDto { + @ApiProperty({ enum: ['UP', 'DOWN'] }) + @IsIn(['UP', 'DOWN']) + direction!: 'UP' | 'DOWN'; +} diff --git a/apps/api/src/outbound/import-preview.processor.spec.ts b/apps/api/src/outbound/import-preview.processor.spec.ts index a9209f1..e26d86b 100644 --- a/apps/api/src/outbound/import-preview.processor.spec.ts +++ b/apps/api/src/outbound/import-preview.processor.spec.ts @@ -4,7 +4,7 @@ import { writeFile } from 'fs/promises'; import sharp from 'sharp'; import { JobStatus, OUTBOUND_IMPORT_COLUMNS } from '@artveris/shared'; import { ImportPreviewProcessor } from './import-preview.processor'; -import { OUTBOUND_IMPORT_MAX_ROWS } from './outbound-import.util'; +import { outboundImportPreviewImageKey, OUTBOUND_IMPORT_MAX_ROWS } from './outbound-import.util'; type SheetCell = string | number | Date | null; @@ -45,12 +45,11 @@ async function oversizedPng(): Promise { } function traceCode(shortCode: string, batchNo = 'B1') { - return { id: BigInt(shortCode), shortCode, outTime: null, outImages: null, batch: { batchNo } }; + return { id: BigInt(shortCode), shortCode, outbound: null, batch: { batchNo } }; } function createHarness(zipBuffer: Buffer, codes: any[] = []) { const persistedRows: any[] = []; - let savedSequence = 0; const outboundImportRow = { findMany: jest.fn().mockImplementation(async () => persistedRows.map((row) => ({ outImageKeys: row.outImageKeys }))), deleteMany: jest.fn().mockResolvedValue({ count: 0 }), @@ -86,10 +85,7 @@ function createHarness(zipBuffer: Buffer, codes: any[] = []) { downloadToFile: jest.fn().mockImplementation(async (_key: string, filePath: string) => { await writeFile(filePath, zipBuffer); }), - save: jest.fn().mockImplementation(async (_data: Buffer, name: string) => { - savedSequence += 1; - return { key: `temp/${savedSequence}-${name}`, url: `/uploads/${savedSequence}-${name}`, name }; - }), + putKey: jest.fn().mockImplementation(async (key: string) => `/uploads/${key}`), remove: jest.fn().mockResolvedValue(undefined), }; const jobs = { @@ -110,7 +106,7 @@ async function process(processor: ImportPreviewProcessor): Promise { describe('ImportPreviewProcessor', () => { it('accepts a valid ZIP with a long archive comment', async () => { const zip = await buildZip({ - rows: [['111111111111', 'B1', '2026-07-04 10:00', '', '']], + rows: [['111111111111', 'B1', '2026-07-04 10:00', '']], comment: 'x'.repeat(100), }); const harness = createHarness(zip, [traceCode('111111111111')]); @@ -122,7 +118,7 @@ describe('ImportPreviewProcessor', () => { it('interprets an Excel date cell as a Shanghai wall-clock value', async () => { const zip = await buildZip({ - rows: [['111111111111', 'B1', new Date('2026-07-04T10:00:00.000Z'), '', '']], + rows: [['111111111111', 'B1', new Date('2026-07-04T10:00:00.000Z'), '']], }); const harness = createHarness(zip, [traceCode('111111111111')]); @@ -135,7 +131,7 @@ describe('ImportPreviewProcessor', () => { }); it('rejects a row without outbound time', async () => { - const zip = await buildZip({ rows: [['111111111111', 'B1', '', '', '']] }); + const zip = await buildZip({ rows: [['111111111111', 'B1', '', '']] }); const harness = createHarness(zip, [traceCode('111111111111')]); await process(harness.processor); @@ -177,20 +173,58 @@ describe('ImportPreviewProcessor', () => { }); }); - it('stores a separately keyed image for each row that references the same ZIP path', async () => { + it('rejects images outside a 12-digit trace-code directory', async () => { + const zip = await buildZip({ + rows: [['111111111111', 'B1', '2026-07-04 10:00', '']], + images: { 'images/front.jpg': await jpeg() }, + }); + const harness = createHarness(zip, [traceCode('111111111111')]); + + await process(harness.processor); + + expect(harness.persistedRows).toHaveLength(0); + expect(harness.prisma.job.update).toHaveBeenCalledWith({ + where: { id: 'job-1' }, + data: expect.objectContaining({ status: JobStatus.FAILED, error: expect.stringContaining('images/<12位追溯码>/') }), + }); + }); + + it('rejects an image directory whose trace code is absent from xlsx', async () => { + const zip = await buildZip({ + rows: [['111111111111', 'B1', '2026-07-04 10:00', '']], + images: { 'images/222222222222/front.jpg': await jpeg() }, + }); + const harness = createHarness(zip, [traceCode('111111111111')]); + + await process(harness.processor); + + expect(harness.persistedRows).toHaveLength(0); + expect(harness.prisma.job.update).toHaveBeenCalledWith({ + where: { id: 'job-1' }, + data: expect.objectContaining({ + status: JobStatus.FAILED, + error: '图片目录对应的追溯码未出现在 xlsx 中:222222222222', + }), + }); + }); + + it('automatically assigns images from each trace-code directory', async () => { const sharedImage = await jpeg(); const zip = await buildZip({ rows: [ - ['111111111111', 'B1', '2026-07-04 10:00', 'images/common.jpg', 'first'], - ['222222222222', 'B1', '2026-07-04 10:01', 'images/common.jpg', 'second'], + ['111111111111', 'B1', '2026-07-04 10:00', 'first'], + ['222222222222', 'B1', '2026-07-04 10:01', 'second'], ], - images: { 'images/common.jpg': sharedImage }, + images: { + 'images/111111111111/common.jpg': sharedImage, + 'images/222222222222/common.jpg': sharedImage, + }, }); const harness = createHarness(zip, [traceCode('111111111111'), traceCode('222222222222')]); await process(harness.processor); - expect(harness.storage.save).toHaveBeenCalledTimes(2); + expect(harness.storage.putKey).toHaveBeenCalledTimes(2); expect(harness.persistedRows).toHaveLength(2); expect(harness.persistedRows.map((row) => row.status)).toEqual(['VALID', 'VALID']); const keys = harness.persistedRows.map((row) => row.outImageKeys[0].key); @@ -201,56 +235,80 @@ describe('ImportPreviewProcessor', () => { }); }); - it('validates all referenced images before saving any of them', async () => { + it('overwrites the same deterministic preview key when a job is delivered again', async () => { + const imagePath = 'images/111111111111/front.jpg'; const zip = await buildZip({ - rows: [['111111111111', 'B1', '2026-07-04 10:00', 'images/present.jpg;images/missing.jpg', '']], - images: { 'images/present.jpg': await jpeg() }, + rows: [['111111111111', 'B1', '2026-07-04 10:00', '']], + images: { [imagePath]: await jpeg() }, + }); + const harness = createHarness(zip, [traceCode('111111111111')]); + + await process(harness.processor); + await process(harness.processor); + + const expectedKey = outboundImportPreviewImageKey('session-1', imagePath); + expect(harness.storage.putKey).toHaveBeenCalledTimes(2); + expect(harness.storage.putKey.mock.calls.map(([key]) => key)).toEqual([expectedKey, expectedKey]); + }); + + it('validates every automatically assigned image before saving any of them', async () => { + const zip = await buildZip({ + rows: [['111111111111', 'B1', '2026-07-04 10:00', '']], + images: { + 'images/111111111111/present.jpg': await jpeg(), + 'images/111111111111/disguised.jpg': await png(), + }, }); const harness = createHarness(zip, [traceCode('111111111111')]); await process(harness.processor); - expect(harness.storage.save).not.toHaveBeenCalled(); + expect(harness.storage.putKey).not.toHaveBeenCalled(); expect(harness.storage.remove).toHaveBeenCalledWith('zip-key'); expect(harness.persistedRows[0]).toMatchObject({ status: 'INVALID', - reason: '图片不存在:images/missing.jpg', + reason: '图片实际格式与扩展名不一致:images/111111111111/disguised.jpg', outImageKeys: null, }); }); it('keeps a failed image cleanup key attached to the invalid row for scheduled cleanup', async () => { const zip = await buildZip({ - rows: [['111111111111', 'B1', '2026-07-04 10:00', 'images/first.jpg;images/second.jpg', '']], - images: { 'images/first.jpg': await jpeg(), 'images/second.jpg': await jpeg() }, + rows: [['111111111111', 'B1', '2026-07-04 10:00', '']], + images: { + 'images/111111111111/first.jpg': await jpeg(), + 'images/111111111111/second.jpg': await jpeg(), + }, }); const harness = createHarness(zip, [traceCode('111111111111')]); - harness.storage.save - .mockResolvedValueOnce({ key: 'temp/first.jpg', url: '/uploads/first.jpg', name: 'first.jpg' }) + const firstKey = outboundImportPreviewImageKey('session-1', 'images/111111111111/first.jpg'); + harness.storage.putKey + .mockResolvedValueOnce(`/uploads/${firstKey}`) .mockRejectedValueOnce(new Error('save second failed')); harness.storage.remove.mockRejectedValueOnce(new Error('storage unavailable')); await process(harness.processor); - expect(harness.storage.remove).toHaveBeenCalledWith('temp/first.jpg'); + expect(harness.storage.remove).toHaveBeenCalledWith(firstKey); expect(harness.persistedRows[0]).toMatchObject({ status: 'INVALID', reason: 'save second failed', - outImageKeys: [{ key: 'temp/first.jpg' }], + outImageKeys: [{ key: firstKey }], }); }); it('cleans a saved image when the preview heartbeat loses ownership after the storage write', async () => { const zip = await buildZip({ - rows: [['111111111111', 'B1', '2026-07-04 10:00', 'images/front.jpg', '']], - images: { 'images/front.jpg': await jpeg() }, + rows: [['111111111111', 'B1', '2026-07-04 10:00', '']], + images: { 'images/111111111111/front.jpg': await jpeg() }, }); const harness = createHarness(zip, [traceCode('111111111111')]); + const imageKey = outboundImportPreviewImageKey('session-1', 'images/111111111111/front.jpg'); let now = 0; const clock = jest.spyOn(Date, 'now').mockImplementation(() => now); - harness.storage.save.mockImplementationOnce(async () => { + harness.storage.putKey.mockImplementationOnce(async () => { now = 61_000; - return { key: 'temp/saved-before-heartbeat.jpg', url: '/uploads/saved.jpg', name: 'front.jpg' }; + return `/uploads/${imageKey}`; }); harness.jobs.progress.mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 }); try { @@ -259,7 +317,7 @@ describe('ImportPreviewProcessor', () => { clock.mockRestore(); } - expect(harness.storage.remove).toHaveBeenCalledWith('temp/saved-before-heartbeat.jpg'); + expect(harness.storage.remove).toHaveBeenCalledWith(imageKey); expect(harness.persistedRows[0]).toMatchObject({ status: 'INVALID', reason: '导入预览任务状态已变化', @@ -269,10 +327,11 @@ describe('ImportPreviewProcessor', () => { it('does not replace rows when a stalled preview worker loses the session claim', async () => { const zip = await buildZip({ - rows: [['111111111111', 'B1', '2026-07-04 10:00', 'images/front.jpg', '']], - images: { 'images/front.jpg': await jpeg() }, + rows: [['111111111111', 'B1', '2026-07-04 10:00', '']], + images: { 'images/111111111111/front.jpg': await jpeg() }, }); const harness = createHarness(zip, [traceCode('111111111111')]); + const imageKey = outboundImportPreviewImageKey('session-1', 'images/111111111111/front.jpg'); harness.prisma.outboundImportSession.updateMany .mockResolvedValueOnce({ count: 1 }) .mockResolvedValueOnce({ count: 0 }) @@ -283,7 +342,7 @@ describe('ImportPreviewProcessor', () => { expect(harness.prisma.outboundImportRow.deleteMany).not.toHaveBeenCalled(); expect(harness.prisma.outboundImportRow.createMany).not.toHaveBeenCalled(); expect(harness.persistedRows).toHaveLength(0); - expect(harness.storage.remove).toHaveBeenCalledWith('temp/1-front.jpg'); + expect(harness.storage.remove).toHaveBeenCalledWith(imageKey); expect(harness.prisma.job.update).not.toHaveBeenCalled(); }); @@ -313,10 +372,11 @@ describe('ImportPreviewProcessor', () => { it('keeps images referenced by rows when the preview transaction result is unknown', async () => { const zip = await buildZip({ - rows: [['111111111111', 'B1', '2026-07-04 10:00', 'images/front.jpg', '']], - images: { 'images/front.jpg': await jpeg() }, + rows: [['111111111111', 'B1', '2026-07-04 10:00', '']], + images: { 'images/111111111111/front.jpg': await jpeg() }, }); const harness = createHarness(zip, [traceCode('111111111111')]); + const imageKey = outboundImportPreviewImageKey('session-1', 'images/111111111111/front.jpg'); harness.prisma.$transaction .mockImplementationOnce(async (callback: (tx: unknown) => unknown) => callback({ outboundImportRow: harness.prisma.outboundImportRow, @@ -335,38 +395,38 @@ describe('ImportPreviewProcessor', () => { await process(harness.processor); expect(harness.persistedRows).toHaveLength(1); - expect(harness.storage.remove).not.toHaveBeenCalledWith('temp/1-front.jpg'); + expect(harness.storage.remove).not.toHaveBeenCalledWith(imageKey); }); it('rejects an image whose bytes do not match its extension', async () => { const zip = await buildZip({ - rows: [['111111111111', 'B1', '2026-07-04 10:00', 'images/disguised.jpg', '']], - images: { 'images/disguised.jpg': await png() }, + rows: [['111111111111', 'B1', '2026-07-04 10:00', '']], + images: { 'images/111111111111/disguised.jpg': await png() }, }); const harness = createHarness(zip, [traceCode('111111111111')]); await process(harness.processor); - expect(harness.storage.save).not.toHaveBeenCalled(); + expect(harness.storage.putKey).not.toHaveBeenCalled(); expect(harness.persistedRows[0]).toMatchObject({ status: 'INVALID', - reason: '图片实际格式与扩展名不一致:images/disguised.jpg', + reason: '图片实际格式与扩展名不一致:images/111111111111/disguised.jpg', }); }); it('rejects an image over 40 million pixels with a localized error', async () => { const zip = await buildZip({ - rows: [['111111111111', 'B1', '2026-07-04 10:00', 'images/oversized.png', '']], - images: { 'images/oversized.png': await oversizedPng() }, + rows: [['111111111111', 'B1', '2026-07-04 10:00', '']], + images: { 'images/111111111111/oversized.png': await oversizedPng() }, }); const harness = createHarness(zip, [traceCode('111111111111')]); await process(harness.processor); - expect(harness.storage.save).not.toHaveBeenCalled(); + expect(harness.storage.putKey).not.toHaveBeenCalled(); expect(harness.persistedRows[0]).toMatchObject({ status: 'INVALID', - reason: '图片像素尺寸超过限制:images/oversized.png', + reason: '图片像素尺寸超过限制:images/111111111111/oversized.png', }); }); diff --git a/apps/api/src/outbound/import-preview.processor.ts b/apps/api/src/outbound/import-preview.processor.ts index bc50ed7..a59f1ed 100644 --- a/apps/api/src/outbound/import-preview.processor.ts +++ b/apps/api/src/outbound/import-preview.processor.ts @@ -13,7 +13,7 @@ import { isOutbound } from './outbound.util'; import { assertArchiveLimits, assertArchiveActualSize, - assertStoredImageBudget, + assertOutboundImportDiskCapacity, assertZipEntryCount, canonicalImagePath, cellToString, @@ -24,7 +24,6 @@ import { OUTBOUND_IMPORT_MAX_COLUMNS, OUTBOUND_IMPORT_MAX_IMAGE_PIXELS, OUTBOUND_IMPORT_MAX_IMAGE_SIZE, - OUTBOUND_IMPORT_MAX_IMAGES_PER_ROW, OUTBOUND_IMPORT_MAX_ROWS, OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS, OUTBOUND_IMPORT_PREVIEW_TEMP_PREFIX, @@ -33,6 +32,7 @@ import { OUTBOUND_IMPORT_MAX_XLSX_SIZE, OUTBOUND_IMPORT_MAX_XLSX_UNCOMPRESSED_SIZE, OUTBOUND_IMPORT_MAX_ZIP_ENTRIES, + outboundImportPreviewImageKey, parseOutboundDate, readArchiveEntryBuffer, } from './outbound-import.util'; @@ -43,6 +43,7 @@ interface PreviewJobData { jobId: string; sessionId: string; fileKey: string; + fileSize?: number; } interface ParsedSheetRow { @@ -55,6 +56,10 @@ interface StoredImage { url: string; name: string; type: string; + mimeType: string; + size: number; + width: number; + height: number; } interface ArchivedImage { @@ -75,7 +80,7 @@ export class ImportPreviewProcessor extends WorkerHost { } async process(job: Job): Promise { - const { jobId, sessionId, fileKey } = job.data; + const { jobId, sessionId, fileKey, fileSize = 0 } = job.data; const createdImageKeys = new Set(); let rowsPersisted = false; let workingDir = ''; @@ -144,6 +149,7 @@ export class ImportPreviewProcessor extends WorkerHost { lastHeartbeatAt = Date.now(); }; await ensureOutboundImportTempDir(); + await assertOutboundImportDiskCapacity(fileSize, 1); workingDir = await mkdtemp(join(OUTBOUND_IMPORT_TEMP_DIR, OUTBOUND_IMPORT_PREVIEW_TEMP_PREFIX)); const archivePath = join(workingDir, 'source.zip'); await this.storage.downloadToFile(fileKey, archivePath, { @@ -199,14 +205,23 @@ export class ImportPreviewProcessor extends WorkerHost { ); const imageEntries = new Map(); + const imagesByShortCode = new Map(); for (const entry of files) { const name = entry.path.replace(/\\/g, '/'); if (name === xlsxName || name === '说明.txt') continue; const path = normalizeImagePath(name); + if (!/^images\/\d{12}\//i.test(path)) { + throw new Error(`图片必须位于 images/<12位追溯码>/ 目录:${path}`); + } const canonical = canonicalImagePath(path); if (imageEntries.has(canonical)) throw new Error(`ZIP 中存在重复图片路径:${path}`); if (Number(entry.uncompressedSize) > OUTBOUND_IMPORT_MAX_IMAGE_SIZE) throw new Error(`图片超过 100MB:${path}`); - imageEntries.set(canonical, { path, entry }); + const image = { path, entry }; + imageEntries.set(canonical, image); + const shortCode = path.split('/')[1]; + const grouped = imagesByShortCode.get(shortCode) ?? []; + grouped.push(image); + imagesByShortCode.set(shortCode, grouped); } const workbook = new ExcelJS.Workbook(); @@ -260,12 +275,19 @@ export class ImportPreviewProcessor extends WorkerHost { throw new Error(`导入数据超过 ${OUTBOUND_IMPORT_MAX_ROWS} 行限制`); } + const sheetCodeSet = new Set(sheetRows.map((row) => row.values.shortCode)); + for (const directoryCode of imagesByShortCode.keys()) { + if (!sheetCodeSet.has(directoryCode)) { + throw new Error(`图片目录对应的追溯码未出现在 xlsx 中:${directoryCode}`); + } + } + const codeMap = new Map(); const shortCodes = [...new Set(sheetRows.map((row) => row.values.shortCode).filter((code) => TRACE_CODE_PATTERN.test(code)))]; for (let offset = 0; offset < shortCodes.length; offset += 1000) { const codes = await this.prisma.traceCode.findMany({ where: { shortCode: { in: shortCodes.slice(offset, offset + 1000) } }, - include: { batch: true }, + include: { batch: true, outbound: { select: { id: true } } }, }); codes.forEach((code) => codeMap.set(code.shortCode, code)); } @@ -274,8 +296,8 @@ export class ImportPreviewProcessor extends WorkerHost { const rows: any[] = []; let valid = 0; let invalid = 0; - let imageReferenceCount = 0; const validatedImagePaths = new Set(); + const imageMetadata = new Map(); for (const { rowNo, values } of sheetRows) { const result: any = { @@ -309,27 +331,8 @@ export class ImportPreviewProcessor extends WorkerHost { if (outTime === undefined) throw new Error('出库时间不能为空'); if (outTime === null) throw new Error('出库时间格式不正确,请使用 YYYY-MM-DD HH:mm'); - const rawImagePaths = (values.outImages || '') - .split(';') - .map((path) => path.trim()) - .filter(Boolean); - if (rawImagePaths.length > OUTBOUND_IMPORT_MAX_IMAGES_PER_ROW) { - throw new Error(`每行最多填写 ${OUTBOUND_IMPORT_MAX_IMAGES_PER_ROW} 张出库图`); - } - const imagePaths = rawImagePaths.map(normalizeImagePath); - const imagePathSet = new Set(); - const images: ArchivedImage[] = []; - for (const path of imagePaths) { - const canonical = canonicalImagePath(path); - if (imagePathSet.has(canonical)) throw new Error(`同一行重复引用图片:${path}`); - imagePathSet.add(canonical); - const image = imageEntries.get(canonical); - if (!image) throw new Error(`图片不存在:${path}`); - images.push(image); - } - imageReferenceCount += images.length; - assertStoredImageBudget(imageReferenceCount); - + const images = imagesByShortCode.get(values.shortCode) ?? []; + const imagePaths = images.map((image) => image.path); for (const image of images) { const path = image.path; const canonical = canonicalImagePath(path); @@ -361,6 +364,12 @@ export class ImportPreviewProcessor extends WorkerHost { } if ((metadata.pages || 1) > 1) throw new Error(`不支持多帧图片:${path}`); validatedImagePaths.add(canonical); + imageMetadata.set(canonical, { + mimeType: mimeOfImagePath(path), + size: data.length, + width: metadata.width, + height: metadata.height, + }); } const imageItems: StoredImage[] = []; @@ -372,14 +381,23 @@ export class ImportPreviewProcessor extends WorkerHost { `图片超过 100MB:${image.path}`, () => heartbeat(valid, invalid), ); - const saved = await this.storage.save( + const key = outboundImportPreviewImageKey(sessionId, image.path); + const mimeType = mimeOfImagePath(image.path); + const url = await this.storage.putKey( + key, data, - image.path.split('/').pop() || 'outbound.jpg', - mimeOfImagePath(image.path), + mimeType, { requestTimeoutMs: OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS }, ); - createdImageKeys.add(saved.key); - imageItems.push({ key: saved.key, url: saved.url, name: saved.name, type: 'image' }); + createdImageKeys.add(key); + const meta = imageMetadata.get(canonicalImagePath(image.path))!; + imageItems.push({ + key, + url, + name: image.path.split('/').pop() || 'outbound.jpg', + type: 'image', + ...meta, + }); await heartbeat(valid, invalid); } diff --git a/apps/api/src/outbound/import.processor.spec.ts b/apps/api/src/outbound/import.processor.spec.ts index 306c21a..f1f816b 100644 --- a/apps/api/src/outbound/import.processor.spec.ts +++ b/apps/api/src/outbound/import.processor.spec.ts @@ -24,9 +24,7 @@ function traceCode(overrides: Record = {}) { return { id: 11n, shortCode: '111111111111', - outTime: null, - outImages: null, - remark: null, + outbound: null, batch: { batchNo: 'B1' }, artwork: { templateId: 1, archiveNo: 'ARTVERIS-000001' }, ...overrides, @@ -46,7 +44,7 @@ function createHarness(options: { rows?: any[]; code?: any; session?: any | null; - traceUpdateCount?: number; + transactionOutboundExists?: boolean; } = {}) { const initialRows = options.rows ?? [importRow()]; const defaultSession = { @@ -59,6 +57,7 @@ function createHarness(options: { error: null, importJobId: 'job-1', importRunToken: null, + createdBy: 7, updatedAt: new Date('2026-07-04T01:00:00.000Z'), }; const state: { @@ -104,13 +103,6 @@ function createHarness(options: { return { count }; }; const countRows = async ({ where }: any) => state.rows.filter((row) => rowMatches(row, where)).length; - const updateTraceCodeMany = async ({ where, data }: any) => { - const count = - options.traceUpdateCount ?? - (state.code.id === where.id && (where.outTime === undefined || state.code.outTime === where.outTime) ? 1 : 0); - if (count === 1) Object.assign(state.code, data); - return { count }; - }; const updateJob = async ({ where, data }: any) => { if (state.job.id !== where.id) throw new Error('job not found'); Object.assign(state.job, data); @@ -136,7 +128,23 @@ function createHarness(options: { count: jest.fn(countRows), }, traceCode: { - updateMany: jest.fn(updateTraceCodeMany), + findUnique: jest.fn().mockImplementation(async () => ({ + outbound: options.transactionOutboundExists + ? { id: 99n } + : state.code.outbound + ? { id: state.code.outbound.id } + : null, + })), + }, + outboundRecord: { + create: jest.fn().mockImplementation(async ({ data }: any) => { + const record = { id: 101n, ...data }; + state.code.outbound = record; + return clone(record); + }), + }, + outboundImage: { + createMany: jest.fn().mockResolvedValue({ count: 0 }), }, job: { update: jest.fn(updateJob), @@ -184,6 +192,10 @@ function createHarness(options: { }; const storage = { copyMedia: jest.fn().mockImplementation(async (items: any[]) => ({ items, keyMap: new Map() })), + read: jest.fn().mockResolvedValue(Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2nS8AAAAASUVORK5CYII=', + 'base64', + )), save: jest.fn().mockResolvedValue({ key: 'unused.xlsx' }), remove: jest.fn().mockResolvedValue(undefined), }; @@ -215,14 +227,16 @@ describe('ImportProcessor', () => { where: { id: 'session-1', status: 'IMPORTING', importJobId: 'job-1' }, data: { importRunToken: expect.any(String) }, }); - expect(harness.tx.traceCode.updateMany).toHaveBeenCalledWith({ - where: { id: 11n, outTime: null }, + expect(harness.tx.outboundRecord.create).toHaveBeenCalledWith({ data: { + traceCodeId: 11n, outTime: row.outTime, - outImages: expect.anything(), remark: 'ok', + createdBy: 7, + updatedBy: 7, }, }); + expect(harness.tx.outboundImage.createMany).not.toHaveBeenCalled(); expect(harness.tx.outboundImportRow.updateMany).toHaveBeenCalledWith({ where: { id: 1n, status: 'VALID' }, data: { status: 'IMPORTED', reason: null, outImageKeys: [] }, @@ -269,7 +283,7 @@ describe('ImportProcessor', () => { await process(harness.processor); expect(harness.storage.copyMedia).toHaveBeenCalledWith( - [{ key: 'temp/image.jpg', name: 'image.jpg', type: 'image' }], + [expect.objectContaining({ key: 'temp/image.jpg', name: 'image.jpg', type: 'image' })], '1/ARTVERIS-000001/111111111111', '出库实况', expect.any(Function), @@ -297,7 +311,7 @@ describe('ImportProcessor', () => { it('rejects a concurrent duplicate outbound atomically and removes only the uncommitted copies', async () => { const row = importRow({ outImageKeys: [{ key: 'temp/image.jpg', name: 'image.jpg', type: 'image' }] }); - const harness = createHarness({ rows: [row], traceUpdateCount: 0 }); + const harness = createHarness({ rows: [row], transactionOutboundExists: true }); harness.storage.copyMedia.mockImplementation(async (_items: any[], _dir: string, _baseName: string, onPlanned: any) => { await onPlanned(['final/image.jpg']); return { @@ -351,13 +365,13 @@ describe('ImportProcessor', () => { })); }); - it('rechecks the batch number before copying media or updating the trace code', async () => { + it('rechecks the batch number before copying media or creating the outbound record', async () => { const harness = createHarness({ code: traceCode({ batch: { batchNo: 'B2' } }) }); await process(harness.processor); expect(harness.storage.copyMedia).not.toHaveBeenCalled(); - expect(harness.tx.traceCode.updateMany).not.toHaveBeenCalled(); + expect(harness.tx.outboundRecord.create).not.toHaveBeenCalled(); expect(harness.tx.outboundImportRow.updateMany).toHaveBeenCalledWith({ where: { id: 1n, status: 'VALID' }, data: { status: 'FAILED', reason: '批次编号不匹配,实际为 B2' }, @@ -373,7 +387,7 @@ describe('ImportProcessor', () => { await process(harness.processor); - expect(harness.tx.traceCode.updateMany).toHaveBeenCalledTimes(1); + expect(harness.tx.outboundRecord.create).toHaveBeenCalledTimes(1); expect(harness.state.session).toEqual( expect.objectContaining({ status: 'IMPORTED', validCount: 2, invalidCount: 0 }), ); @@ -425,7 +439,7 @@ describe('ImportProcessor', () => { .filter((call: any) => call.data.importRunToken); expect(claims).toHaveLength(2); expect(claims[0].data.importRunToken).not.toBe(claims[1].data.importRunToken); - expect(harness.tx.traceCode.updateMany).toHaveBeenCalledTimes(1); + expect(harness.tx.outboundRecord.create).toHaveBeenCalledTimes(1); expect(harness.tx.outboundImportRow.updateMany).toHaveBeenCalledTimes(3); expect(harness.tx.outboundImportSession.update).toHaveBeenCalledTimes(1); expect(harness.tx.job.update).toHaveBeenCalledTimes(1); @@ -484,7 +498,7 @@ describe('ImportProcessor', () => { expect(harness.jobs.start).not.toHaveBeenCalled(); expect(harness.prisma.outboundImportRow.findMany).not.toHaveBeenCalled(); - expect(harness.tx.traceCode.updateMany).not.toHaveBeenCalled(); + expect(harness.tx.outboundRecord.create).not.toHaveBeenCalled(); expect(harness.state.session).toEqual( expect.objectContaining({ status: 'IMPORTING', importJobId: 'job-1', importRunToken: null }), ); diff --git a/apps/api/src/outbound/import.processor.ts b/apps/api/src/outbound/import.processor.ts index 27e9537..1535bd6 100644 --- a/apps/api/src/outbound/import.processor.ts +++ b/apps/api/src/outbound/import.processor.ts @@ -3,12 +3,14 @@ import { Logger } from '@nestjs/common'; import { Job } from 'bullmq'; import { randomUUID } from 'crypto'; import { Prisma } from '@prisma/client'; +import sharp from 'sharp'; import { JobStatus, QUEUE_NAMES } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; import { StorageService } from '../storage/storage.service'; import { JobsService } from '../jobs/jobs.service'; import { isOutbound } from './outbound.util'; import { OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS } from './outbound-import.util'; +import { storageContentType } from '../storage/storage.service'; interface ImportJobData { jobId: string; @@ -20,6 +22,10 @@ interface ImportImage { url?: string; name?: string; type?: string; + mimeType?: string; + size?: number; + width?: number; + height?: number; } function jsonArray(value: unknown): T[] { @@ -58,6 +64,7 @@ export class ImportProcessor extends WorkerHost { invalidCount: true, error: true, importJobId: true, + createdBy: true, }, }); if (!session) { @@ -118,7 +125,7 @@ export class ImportProcessor extends WorkerHost { let progressFail = failedBefore; for (const row of rows) { try { - await this.importRow(row, sessionId, runToken); + await this.importRow(row, sessionId, runToken, session.createdBy ?? undefined); progressSuccess++; } catch (error) { if (error instanceof ImportRunSupersededError) return; @@ -199,7 +206,7 @@ export class ImportProcessor extends WorkerHost { outImageKeys: Prisma.JsonValue | null; preview: Prisma.JsonValue | null; remark: string | null; - }, sessionId: string, runToken: string): Promise { + }, sessionId: string, runToken: string, createdBy?: number): Promise { if (!row.shortCode) throw new Error('追溯码为空'); if (!row.outTime) throw new Error('出库时间为空'); if (!(await this.ownsRun(sessionId, runToken))) throw new ImportRunSupersededError(); @@ -209,6 +216,7 @@ export class ImportProcessor extends WorkerHost { include: { batch: { select: { batchNo: true } }, artwork: { select: { templateId: true, archiveNo: true } }, + outbound: { select: { id: true } }, }, }); if (!code) throw new Error('追溯码不存在'); @@ -219,15 +227,25 @@ export class ImportProcessor extends WorkerHost { let imageItems = jsonArray(row.outImageKeys) .filter((item) => item && typeof item.key === 'string' && item.key) - .map((item) => ({ key: item.key, name: item.name, type: item.type || 'image' })); + .map((item) => ({ ...item, key: item.key, name: item.name, type: item.type || 'image' })); + for (const item of imageItems) { + if (item.width && item.height && item.size && item.mimeType) continue; + const data = await this.storage.read(item.key); + const metadata = await sharp(data).metadata(); + if (!metadata.width || !metadata.height) throw new Error(`无法读取出库图片尺寸:${item.name || item.key}`); + item.width = metadata.width; + item.height = metadata.height; + item.size = data.length; + item.mimeType = storageContentType(item.key); + } const preview = row.preview && typeof row.preview === 'object' && !Array.isArray(row.preview) ? row.preview as Record : {}; let pendingCopiedKeys = jsonArray(preview.pendingCopiedKeys).filter(Boolean); let copiedKeys: string[] = []; let sourceKeys: string[] = []; - if (imageItems.length && code.artwork.archiveNo) { - const dir = `${code.artwork.templateId}/${code.artwork.archiveNo}/${code.shortCode}`; + if (imageItems.length) { + const dir = `${code.artwork.templateId}/${code.artwork.archiveNo || '未归档'}/${code.shortCode}`; const copied = await this.storage.copyMedia(imageItems, dir, '出库实况', async (plannedKeys) => { pendingCopiedKeys = [...new Set([...pendingCopiedKeys, ...plannedKeys])]; await this.prisma.$transaction(async (tx) => { @@ -251,15 +269,35 @@ export class ImportProcessor extends WorkerHost { try { await this.prisma.$transaction(async (tx) => { await this.assertRunOwnership(tx, sessionId, runToken); - const updated = await tx.traceCode.updateMany({ - where: { id: code.id, outTime: null }, + const current = await tx.traceCode.findUnique({ + where: { id: code.id }, + select: { outbound: { select: { id: true } } }, + }); + if (!current || current.outbound) throw new Error('该追溯码已登记出库,不可重复出库'); + const outbound = await tx.outboundRecord.create({ data: { - outTime: row.outTime, - outImages: imageItems.length ? imageItems : Prisma.DbNull, + traceCodeId: code.id, + outTime: row.outTime!, remark: row.remark || null, + createdBy, + updatedBy: createdBy, }, }); - if (updated.count !== 1) throw new Error('该追溯码已登记出库,不可重复出库'); + if (imageItems.length) { + await tx.outboundImage.createMany({ + data: imageItems.map((image, sortOrder) => ({ + outboundRecordId: outbound.id, + fileKey: image.key, + fileName: (image.name || image.key.split('/').pop() || '出库实况图').slice(0, 191), + mimeType: image.mimeType || storageContentType(image.key), + size: BigInt(image.size || 0), + width: image.width || 1, + height: image.height || 1, + sortOrder, + createdBy, + })), + }); + } const imported = await tx.outboundImportRow.updateMany({ where: { id: row.id, status: 'VALID' }, data: { status: 'IMPORTED', reason: null, outImageKeys: imageItems }, diff --git a/apps/api/src/outbound/outbound-import-cleanup.service.spec.ts b/apps/api/src/outbound/outbound-import-cleanup.service.spec.ts index ebf7cfd..ec617c1 100644 --- a/apps/api/src/outbound/outbound-import-cleanup.service.spec.ts +++ b/apps/api/src/outbound/outbound-import-cleanup.service.spec.ts @@ -1,5 +1,6 @@ import { JobStatus, JobType, OutboundImportRowStatus, OutboundImportSessionStatus } from '@prisma/client'; import { OutboundImportCleanupService } from './outbound-import-cleanup.service'; +import { outboundImportPreviewStoragePrefix } from './outbound-import.util'; describe('OutboundImportCleanupService', () => { let prisma: { @@ -13,7 +14,7 @@ describe('OutboundImportCleanupService', () => { job: { findMany: jest.Mock; updateMany: jest.Mock; update: jest.Mock }; $transaction: jest.Mock; }; - let storage: { remove: jest.Mock }; + let storage: { remove: jest.Mock; listKeys: jest.Mock }; let importQueue: { getJob: jest.Mock; add: jest.Mock }; let previewQueue: { getJob: jest.Mock; add: jest.Mock }; let service: OutboundImportCleanupService; @@ -39,7 +40,10 @@ describe('OutboundImportCleanupService', () => { $transaction: jest.fn(), }; prisma.$transaction.mockImplementation(async (callback: (tx: typeof prisma) => unknown) => callback(prisma)); - storage = { remove: jest.fn().mockResolvedValue(undefined) }; + storage = { + remove: jest.fn().mockResolvedValue(undefined), + listKeys: jest.fn().mockResolvedValue([]), + }; importQueue = { getJob: jest.fn().mockResolvedValue(undefined), add: jest.fn().mockResolvedValue(undefined) }; previewQueue = { getJob: jest.fn().mockResolvedValue(undefined), add: jest.fn().mockResolvedValue(undefined) }; service = new OutboundImportCleanupService( @@ -119,6 +123,28 @@ describe('OutboundImportCleanupService', () => { }); }); + it('removes preview objects that were written before their database rows', async () => { + const prefix = outboundImportPreviewStoragePrefix('session-orphan'); + mockSessionSearch([{ id: 'session-orphan', status: OutboundImportSessionStatus.PARSING }]); + prisma.outboundImportSession.updateMany.mockResolvedValueOnce({ count: 1 }); + prisma.outboundImportSession.findUnique.mockResolvedValue({ + id: 'session-orphan', + status: OutboundImportSessionStatus.EXPIRED, + fileKey: null, + rows: [], + }); + storage.listKeys.mockResolvedValueOnce([`${prefix}path-hash.jpg`]); + prisma.outboundImportSession.deleteMany.mockResolvedValueOnce({ count: 1 }); + + await service.cleanupExpiredPreviewSessions(); + + expect(storage.listKeys).toHaveBeenCalledWith(prefix); + expect(storage.remove).toHaveBeenCalledWith(`${prefix}path-hash.jpg`); + expect(prisma.outboundImportSession.deleteMany).toHaveBeenCalledWith({ + where: { id: 'session-orphan', status: OutboundImportSessionStatus.EXPIRED }, + }); + }); + it('retries a stale EXPIRED session without claiming it again', async () => { mockSessionSearch([{ id: 'session-expired', status: OutboundImportSessionStatus.EXPIRED }]); prisma.outboundImportSession.findUnique.mockResolvedValue({ diff --git a/apps/api/src/outbound/outbound-import-cleanup.service.ts b/apps/api/src/outbound/outbound-import-cleanup.service.ts index 4a6dc88..db37e91 100644 --- a/apps/api/src/outbound/outbound-import-cleanup.service.ts +++ b/apps/api/src/outbound/outbound-import-cleanup.service.ts @@ -19,6 +19,7 @@ import { OUTBOUND_IMPORT_TEMP_DIR, OUTBOUND_IMPORT_UPLOAD_TEMP_PREFIX, OUTBOUND_IMPORT_PREVIEW_TEMP_PREFIX, + outboundImportPreviewStoragePrefix, } from './outbound-import.util'; function collectImageKeys(value: Prisma.JsonValue | null): string[] { @@ -145,7 +146,12 @@ export class OutboundImportCleanupService implements OnModuleInit { const name = record.type === JobType.IMPORT_OUTBOUND ? 'import' : 'preview'; const data = record.type === JobType.IMPORT_OUTBOUND ? { jobId: record.id, sessionId } - : { jobId: record.id, sessionId, fileKey: typeof payload.fileKey === 'string' ? payload.fileKey : '' }; + : { + jobId: record.id, + sessionId, + fileKey: typeof payload.fileKey === 'string' ? payload.fileKey : '', + fileSize: typeof payload.fileSize === 'number' ? payload.fileSize : 0, + }; try { const queued = await queue.getJob(record.id); if (queued) { @@ -271,6 +277,7 @@ export class OutboundImportCleanupService implements OnModuleInit { if (!session || session.status !== OutboundImportSessionStatus.EXPIRED) continue; const keys = new Set(); + let cleanupFailed = false; if (session.fileKey) keys.add(session.fileKey); for (const row of session.rows) { if (row.status === OutboundImportRowStatus.IMPORTED) continue; @@ -278,7 +285,15 @@ export class OutboundImportCleanupService implements OnModuleInit { collectPreviewKeys(row.preview as Prisma.JsonValue | null).forEach((key) => keys.add(key)); } - let cleanupFailed = false; + try { + const prefix = outboundImportPreviewStoragePrefix(session.id); + const prefixKeys = await this.storage.listKeys(prefix); + prefixKeys.forEach((key) => keys.add(key)); + } catch (error) { + cleanupFailed = true; + this.logger.warn(`Failed to list outbound preview objects for session ${session.id}: ${(error as Error).message}`); + } + for (const key of keys) { try { await this.storage.remove(key); diff --git a/apps/api/src/outbound/outbound-import.util.spec.ts b/apps/api/src/outbound/outbound-import.util.spec.ts index 42b0773..dd34d8d 100644 --- a/apps/api/src/outbound/outbound-import.util.spec.ts +++ b/apps/api/src/outbound/outbound-import.util.spec.ts @@ -1,7 +1,6 @@ import { assertArchiveActualSize, assertArchiveLimits, - assertStoredImageBudget, assertZipEntryCount, canonicalImagePath, cellToString, @@ -53,7 +52,7 @@ describe('parseOutboundDate', () => { describe('normalizeImagePath', () => { it.each([ ['images/front.jpg', 'images/front.jpg'], - [' image/front.PNG ', 'images/front.PNG'], + [' images/front.PNG ', 'images/front.PNG'], ['images/批次 A/正面 (1).webp', 'images/批次 A/正面 (1).webp'], ])('normalizes a safe image path: %s', (input, expected) => { expect(normalizeImagePath(input)).toBe(expected); @@ -73,6 +72,7 @@ describe('parseOutboundDate', () => { it('rejects paths outside images and unsupported extensions', () => { expect(() => normalizeImagePath('other/front.jpg')).toThrow(/图片必须位于 images 目录/); + expect(() => normalizeImagePath('image/front.jpg')).toThrow(/图片必须位于 images 目录/); for (const path of ['images/front.gif', 'images/front.svg', 'images/front.jpg.exe']) { expect(() => normalizeImagePath(path)).toThrow(/不支持的图片格式/); } @@ -189,12 +189,6 @@ describe('cellToString', () => { }); }); -describe('assertStoredImageBudget', () => { - it('rejects output amplification by repeated image references', () => { - expect(() => assertStoredImageBudget(20_001)).toThrow('出库图片引用总数超过限制'); - }); -}); - describe('streamed archive limits', () => { const streamed = (...chunks: Buffer[]) => ({ isDirectory: false, diff --git a/apps/api/src/outbound/outbound-import.util.ts b/apps/api/src/outbound/outbound-import.util.ts index c10423a..663bc10 100644 --- a/apps/api/src/outbound/outbound-import.util.ts +++ b/apps/api/src/outbound/outbound-import.util.ts @@ -1,22 +1,24 @@ -import { mkdir, open } from 'fs/promises'; +import { createHash } from 'crypto'; +import { mkdir, open, statfs } from 'fs/promises'; import { tmpdir } from 'os'; import { resolve } from 'path'; import { Readable } from 'stream'; export const OUTBOUND_IMPORT_MAX_ROWS = 10_000; export const OUTBOUND_IMPORT_MAX_COLUMNS = 64; -export const OUTBOUND_IMPORT_MAX_ZIP_ENTRIES = 20_002; +// 仅用于防止恶意中央目录耗尽内存,不作为业务图片数量限制。 +export const OUTBOUND_IMPORT_MAX_ZIP_ENTRIES = 100_002; export const OUTBOUND_IMPORT_MAX_XLSX_SIZE = 100 * 1024 * 1024; export const OUTBOUND_IMPORT_MAX_XLSX_ENTRIES = 256; export const OUTBOUND_IMPORT_MAX_XLSX_UNCOMPRESSED_SIZE = 500 * 1024 * 1024; export const OUTBOUND_IMPORT_MAX_IMAGE_SIZE = 100 * 1024 * 1024; -export const OUTBOUND_IMPORT_MAX_IMAGES_PER_ROW = 20; export const OUTBOUND_IMPORT_MAX_IMAGE_PIXELS = 40_000_000; -export const OUTBOUND_IMPORT_MAX_IMAGE_REFERENCES = 20_000; export const OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS = 60 * 60 * 1000; export const OUTBOUND_IMPORT_TEMP_DIR = resolve(process.env.ARTVERIS_OUTBOUND_TEMP_DIR || tmpdir()); export const OUTBOUND_IMPORT_UPLOAD_TEMP_PREFIX = 'artveris-outbound-upload-'; export const OUTBOUND_IMPORT_PREVIEW_TEMP_PREFIX = 'artveris-outbound-preview-'; +export const OUTBOUND_IMPORT_PREVIEW_STORAGE_ROOT = 'outbound-preview'; +const OUTBOUND_IMPORT_MIN_FREE_BYTES = 1024 * 1024 * 1024; const ARCHIVE_PROGRESS_INTERVAL_BYTES = 8 * 1024 * 1024; const ZIP_END_RECORD_MAX_SIZE = 65_557; @@ -27,10 +29,39 @@ const ZIP_END_SIGNATURE = 0x06054b50; const ZIP64_LOCATOR_SIGNATURE = 0x07064b50; const ZIP64_END_SIGNATURE = 0x06064b50; +export function outboundImportPreviewStoragePrefix(sessionId: string): string { + if (!/^[A-Za-z0-9_-]+$/.test(sessionId)) throw new Error('Invalid outbound import session id'); + return `${OUTBOUND_IMPORT_PREVIEW_STORAGE_ROOT}/${sessionId}/`; +} + +export function outboundImportPreviewImageKey(sessionId: string, imagePath: string): string { + const canonicalPath = canonicalImagePath(imagePath); + const pathHash = createHash('sha256').update(canonicalPath, 'utf8').digest('hex'); + const extension = mimeOfImagePath(canonicalPath) === 'image/jpeg' + ? '.jpg' + : canonicalPath.slice(canonicalPath.lastIndexOf('.')).toLowerCase(); + return `${outboundImportPreviewStoragePrefix(sessionId)}${pathHash}${extension}`; +} + export async function ensureOutboundImportTempDir(): Promise { await mkdir(OUTBOUND_IMPORT_TEMP_DIR, { recursive: true }); } +export async function assertOutboundImportDiskCapacity(requiredBytes: number, copies = 1): Promise { + await ensureOutboundImportTempDir(); + const fs = await statfs(OUTBOUND_IMPORT_TEMP_DIR); + const available = Number(fs.bavail) * Number(fs.bsize); + const required = Math.max( + OUTBOUND_IMPORT_MIN_FREE_BYTES, + Math.max(0, Math.ceil(requiredBytes)) * Math.max(1, copies), + ); + if (!Number.isFinite(available) || available < required) { + throw new Error( + `出库导入临时磁盘空间不足:至少需要 ${Math.ceil(required / 1024 / 1024)}MB 可用空间`, + ); + } +} + interface ArchiveEntryLike { isDirectory: boolean; header: { size: number }; @@ -141,12 +172,6 @@ export function assertArchiveLimits( } } -export function assertStoredImageBudget(referenceCount: number): void { - if (referenceCount > OUTBOUND_IMPORT_MAX_IMAGE_REFERENCES) { - throw new Error(`出库图片引用总数超过限制(最多 ${OUTBOUND_IMPORT_MAX_IMAGE_REFERENCES} 张)`); - } -} - export async function readArchiveEntryBuffer( entry: Pick, maxBytes: number, @@ -259,7 +284,7 @@ export function parseOutboundDate(value?: string): Date | undefined | null { } export function normalizeImagePath(raw: string): string { - const path = raw.trim().replace(/^image\//i, 'images/'); + const path = raw.trim(); if (!path) return ''; if (path.includes('\\') || path.includes('..') || path.startsWith('/') || /^[a-z]:/i.test(path)) { throw new Error(`图片路径不安全:${raw}`); diff --git a/apps/api/src/outbound/outbound-management.service.spec.ts b/apps/api/src/outbound/outbound-management.service.spec.ts new file mode 100644 index 0000000..ee13c0a --- /dev/null +++ b/apps/api/src/outbound/outbound-management.service.spec.ts @@ -0,0 +1,236 @@ +import { mkdtemp, rm, writeFile } from 'fs/promises'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import sharp from 'sharp'; +import { JobStatus, JobType } from '@artveris/shared'; +import { OutboundService } from './outbound.service'; + +function serviceWith(prisma: any, storage: any = {}) { + const queue = { add: jest.fn().mockResolvedValue({}) }; + return { + service: new OutboundService(prisma, storage, queue as any, queue as any, queue as any), + queue, + }; +} + +describe('OutboundService records and batch jobs', () => { + it('creates or edits one outbound record independently from blockchain state', async () => { + const record = { id: 9n, traceCodeId: 1n, outTime: new Date('2026-07-15T10:00:00.000Z'), remark: '已出库' }; + const prisma = { + traceCode: { findUnique: jest.fn().mockResolvedValue({ id: 1n }) }, + outboundRecord: { upsert: jest.fn().mockResolvedValue(record) }, + }; + const { service } = serviceWith(prisma); + + await expect(service.updateSingle(1n, { outTime: record.outTime.toISOString(), remark: ' 已出库 ' }, 7)) + .resolves.toMatchObject(record); + expect(prisma.outboundRecord.upsert).toHaveBeenCalledWith({ + where: { traceCodeId: 1n }, + create: expect.objectContaining({ traceCodeId: 1n, remark: '已出库', createdBy: 7, updatedBy: 7 }), + update: expect.objectContaining({ remark: '已出库', updatedBy: 7 }), + include: { _count: { select: { images: true } } }, + }); + }); + + it('accepts explicit ID jobs beyond 10000 and leaves processing to the paged worker', async () => { + const ids = Array.from({ length: 10_001 }, (_, index) => String(index + 1)); + const prisma = { + traceCode: { aggregate: jest.fn() }, + job: { + create: jest.fn().mockImplementation(async ({ data }: any) => ({ id: 'job-1', ...data })), + }, + }; + const { service, queue } = serviceWith(prisma); + + await expect(service.createBatchJob({ + selection: { mode: 'IDS', ids }, + outTime: '2026-07-15T10:00:00.000Z', + }, 7)).resolves.toEqual({ jobId: 'job-1', total: 10_001 }); + expect(prisma.traceCode.aggregate).not.toHaveBeenCalled(); + expect(prisma.job.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + type: JobType.BATCH_OUTBOUND, + status: JobStatus.PENDING, + total: 10_001, + }), + }); + expect(queue.add).toHaveBeenCalledWith( + 'batch-outbound', + { jobId: 'job-1' }, + { jobId: 'batch-outbound-job-1' }, + ); + }); + + it('returns image pages without embedding an unbounded image list in the record', async () => { + const images = [{ id: 2n, fileKey: 'a.jpg', fileName: 'a.jpg', mimeType: 'image/jpeg', size: 10n, width: 1, height: 1, sortOrder: 0 }]; + const prisma = { + outboundRecord: { findUnique: jest.fn().mockResolvedValue({ id: 8n }) }, + outboundImage: { + findMany: jest.fn().mockResolvedValue(images), + count: jest.fn().mockResolvedValue(101), + }, + $transaction: jest.fn().mockImplementation(async (operations: any[]) => Promise.all(operations)), + }; + const { service } = serviceWith(prisma, { getUrl: (key: string) => `/uploads/${key}` }); + + await expect(service.listImages(1n, { page: 2, pageSize: 20 })).resolves.toMatchObject({ + items: [expect.objectContaining({ id: 2n, url: '/uploads/a.jpg' })], + total: 101, + page: 2, + pageSize: 20, + }); + expect(prisma.outboundImage.findMany).toHaveBeenCalledWith(expect.objectContaining({ skip: 20, take: 20 })); + }); + + it('moves an image against its global neighbor so page boundaries do not affect ordering', async () => { + const outboundImage = { + findFirst: jest.fn() + .mockResolvedValueOnce({ id: 21n, outboundRecordId: 8n, sortOrder: 20 }) + .mockResolvedValueOnce({ id: 20n, outboundRecordId: 8n, sortOrder: 19 }), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }; + const prisma = { + outboundImage, + $transaction: jest.fn().mockImplementation(async (callback: any) => callback({ outboundImage })), + }; + const { service } = serviceWith(prisma); + + await expect(service.moveImage(1n, 21n, { direction: 'UP' })).resolves.toEqual({ success: true, moved: true }); + expect(outboundImage.findFirst).toHaveBeenNthCalledWith(2, { + where: { + outboundRecordId: 8n, + OR: [{ sortOrder: { lt: 20 } }, { sortOrder: 20, id: { lt: 21n } }], + }, + orderBy: [{ sortOrder: 'desc' }, { id: 'desc' }], + }); + expect(outboundImage.updateMany).toHaveBeenNthCalledWith(1, { + where: { id: 21n, sortOrder: 20 }, + data: { sortOrder: 19 }, + }); + expect(outboundImage.updateMany).toHaveBeenNthCalledWith(2, { + where: { id: 20n, sortOrder: 19 }, + data: { sortOrder: 20 }, + }); + }); + + it('keeps the image record when storage deletion fails so the operation can be retried', async () => { + const prisma = { + outboundImage: { + findFirst: jest.fn().mockResolvedValue({ id: 3n, fileKey: 'outbound/image.jpg' }), + deleteMany: jest.fn(), + }, + }; + const storage = { remove: jest.fn().mockRejectedValue(new Error('storage unavailable')) }; + const { service } = serviceWith(prisma, storage); + + await expect(service.deleteImage(1n, 3n)).rejects.toThrow('storage unavailable'); + expect(prisma.outboundImage.deleteMany).not.toHaveBeenCalled(); + }); +}); + +describe('OutboundService.uploadImage', () => { + let dir: string; + + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'artveris-outbound-image-')); + }); + + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + function harness() { + const outboundImage = { + create: jest.fn().mockResolvedValue({ id: 101n }), + update: jest.fn().mockImplementation(async ({ data }: any) => ({ + id: 101n, + fileKey: 'final/image.jpg', + fileName: 'image.jpg', + mimeType: 'image/jpeg', + size: 100n, + width: 8, + height: 8, + createdAt: new Date(), + ...data, + })), + }; + const prisma = { + traceCode: { + findUnique: jest.fn().mockResolvedValue({ + shortCode: '482731000001', + outbound: { id: 9n }, + artwork: { templateId: 1, archiveNo: 'A1' }, + }), + }, + outboundImage, + $transaction: jest.fn().mockImplementation(async (callback: any) => callback({ outboundImage })), + }; + const storage = { + saveFile: jest.fn().mockResolvedValue({ key: 'temp/image.jpg' }), + relocateMedia: jest.fn().mockResolvedValue({ items: [{ key: 'final/image.jpg' }] }), + remove: jest.fn().mockResolvedValue(undefined), + getUrl: jest.fn((key: string) => `/uploads/${key}`), + }; + return { ...serviceWith(prisma, storage), prisma, storage }; + } + + it('validates and stores a JPG with a unique concurrent-safe order', async () => { + const filePath = join(dir, 'image.jpg'); + const data = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#fff' } }).jpeg().toBuffer(); + await writeFile(filePath, data); + const test = harness(); + + await test.service.uploadImage(1n, { + path: filePath, + originalname: 'image.jpg', + mimetype: 'image/jpeg', + size: data.length, + } as Express.Multer.File, 7); + + expect(test.prisma.outboundImage.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ outboundRecordId: 9n, sortOrder: 0, width: 8, height: 8 }), + }); + expect(test.prisma.outboundImage.update).toHaveBeenCalledWith({ + where: { id: 101n }, + data: { sortOrder: 101 }, + }); + }); + + it('rejects an image over 40 million pixels before storage', async () => { + const filePath = join(dir, 'large.png'); + const data = await sharp({ create: { width: 6325, height: 6325, channels: 3, background: '#000' } }) + .png({ compressionLevel: 9, palette: true }) + .toBuffer(); + await writeFile(filePath, data); + const test = harness(); + + await expect(test.service.uploadImage(1n, { + path: filePath, + originalname: 'large.png', + mimetype: 'image/png', + size: data.length, + } as Express.Multer.File, 7)).rejects.toThrow(/像素/); + expect(test.storage.saveFile).not.toHaveBeenCalled(); + }); + + it('rejects files larger than 100MB and disguised image formats', async () => { + const test = harness(); + await expect(test.service.uploadImage(1n, { + path: join(dir, 'missing.jpg'), + originalname: 'too-large.jpg', + mimetype: 'image/jpeg', + size: 100 * 1024 * 1024 + 1, + } as Express.Multer.File, 7)).rejects.toThrow('100MB'); + + const filePath = join(dir, 'disguised.jpg'); + const png = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#fff' } }).png().toBuffer(); + await writeFile(filePath, png); + await expect(test.service.uploadImage(1n, { + path: filePath, + originalname: 'disguised.jpg', + mimetype: 'image/jpeg', + size: png.length, + } as Express.Multer.File, 7)).rejects.toThrow('实际格式'); + expect(test.storage.saveFile).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/src/outbound/outbound.controller.ts b/apps/api/src/outbound/outbound.controller.ts index 46129d0..0b7f429 100644 --- a/apps/api/src/outbound/outbound.controller.ts +++ b/apps/api/src/outbound/outbound.controller.ts @@ -1,6 +1,7 @@ import { Body, Controller, + Delete, Get, Param, Post, @@ -15,24 +16,40 @@ import { ApiBearerAuth, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagg import { randomUUID } from 'crypto'; import { Response } from 'express'; import { mkdirSync } from 'fs'; +import { rm } from 'fs/promises'; import { diskStorage } from 'multer'; import { RoleType } from '@artveris/shared'; import { OutboundService } from './outbound.service'; -import { OutboundDto } from './dto/outbound.dto'; +import { BatchOutboundDto, MoveOutboundImageDto, OutboundDto, QueryOutboundImagesDto } from './dto/outbound.dto'; import { QueryImportRowsDto } from './dto/import-session.dto'; import { Roles } from '../common/decorators/roles.decorator'; import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator'; import { parseBigId } from '../common/utils/bigint.util'; -import { OUTBOUND_IMPORT_TEMP_DIR, OUTBOUND_IMPORT_UPLOAD_TEMP_PREFIX } from './outbound-import.util'; +import { + assertOutboundImportDiskCapacity, + OUTBOUND_IMPORT_TEMP_DIR, + OUTBOUND_IMPORT_UPLOAD_TEMP_PREFIX, +} from './outbound-import.util'; +import { OUTBOUND_IMPORT_MAX_IMAGE_SIZE } from './outbound-import.util'; mkdirSync(OUTBOUND_IMPORT_TEMP_DIR, { recursive: true }); const outboundImportDiskStorage = diskStorage({ - destination: OUTBOUND_IMPORT_TEMP_DIR, + destination: (req, _file, callback) => { + const contentLength = Number(req.headers['content-length'] || 0); + assertOutboundImportDiskCapacity(Number.isFinite(contentLength) ? contentLength : 0, 3) + .then(() => callback(null, OUTBOUND_IMPORT_TEMP_DIR)) + .catch((error) => callback(error as Error, OUTBOUND_IMPORT_TEMP_DIR)); + }, filename: (_req, _file, callback) => callback(null, `${OUTBOUND_IMPORT_UPLOAD_TEMP_PREFIX}${randomUUID()}.upload`), }); -@ApiTags('出库与上链') +const outboundImageDiskStorage = diskStorage({ + destination: OUTBOUND_IMPORT_TEMP_DIR, + filename: (_req, _file, callback) => callback(null, `outbound-image-upload-${randomUUID()}.upload`), +}); + +@ApiTags('出库') @ApiBearerAuth() @Controller('outbound') export class OutboundController { @@ -40,9 +57,80 @@ export class OutboundController { @Put('trace-codes/:id') @Roles(RoleType.OPERATOR) - @ApiOperation({ summary: '单条登记出库 / 上链信息' }) - updateSingle(@Param('id') id: string, @Body() dto: OutboundDto) { - return this.outboundService.updateSingle(parseBigId(id, '追溯码 ID'), dto); + @ApiOperation({ summary: '单条登记或修改出库信息' }) + updateSingle(@Param('id') id: string, @Body() dto: OutboundDto, @CurrentUser() user: AuthUser) { + return this.outboundService.updateSingle(parseBigId(id, '追溯码 ID'), dto, user.id); + } + + @Get(':id') + @ApiOperation({ summary: '获取单条出库记录' }) + getRecord(@Param('id') id: string) { + return this.outboundService.getRecord(parseBigId(id, '追溯码 ID')); + } + + @Put(':id') + @Roles(RoleType.OPERATOR) + @ApiOperation({ summary: '登记或修改出库记录' }) + updateRecord(@Param('id') id: string, @Body() dto: OutboundDto, @CurrentUser() user: AuthUser) { + return this.outboundService.updateSingle(parseBigId(id, '追溯码 ID'), dto, user.id); + } + + @Post('jobs') + @Roles(RoleType.OPERATOR) + @ApiOperation({ summary: '创建异步批量出库任务' }) + createJob(@Body() dto: BatchOutboundDto, @CurrentUser() user: AuthUser) { + return this.outboundService.createBatchJob(dto, user.id); + } + + @Get(':id/images') + @ApiOperation({ summary: '分页获取出库实况图' }) + images(@Param('id') id: string, @Query() query: QueryOutboundImagesDto) { + return this.outboundService.listImages(parseBigId(id, '追溯码 ID'), query); + } + + @Post(':id/images') + @Roles(RoleType.OPERATOR) + @ApiOperation({ summary: '上传一张出库实况图' }) + @ApiConsumes('multipart/form-data') + @UseInterceptors(FileInterceptor('file', { + storage: outboundImageDiskStorage, + limits: { files: 1, fileSize: OUTBOUND_IMPORT_MAX_IMAGE_SIZE }, + })) + async uploadImage( + @Param('id') id: string, + @UploadedFile() file: Express.Multer.File, + @CurrentUser() user: AuthUser, + ) { + try { + return await this.outboundService.uploadImage(parseBigId(id, '追溯码 ID'), file, user.id); + } finally { + if (file?.path) await rm(file.path, { force: true }).catch(() => undefined); + } + } + + @Delete(':id/images/:imageId') + @Roles(RoleType.OPERATOR) + @ApiOperation({ summary: '删除出库实况图' }) + deleteImage(@Param('id') id: string, @Param('imageId') imageId: string) { + return this.outboundService.deleteImage( + parseBigId(id, '追溯码 ID'), + parseBigId(imageId, '出库图片 ID'), + ); + } + + @Put(':id/images/:imageId/move') + @Roles(RoleType.OPERATOR) + @ApiOperation({ summary: '全局上移或下移一张出库实况图' }) + moveImage( + @Param('id') id: string, + @Param('imageId') imageId: string, + @Body() dto: MoveOutboundImageDto, + ) { + return this.outboundService.moveImage( + parseBigId(id, '追溯码 ID'), + parseBigId(imageId, '出库图片 ID'), + dto, + ); } @Get('import/template') @@ -98,15 +186,4 @@ export class OutboundController { return this.outboundService.commitSession(id, user); } - @Post('import') - @Roles(RoleType.OPERATOR) - @ApiOperation({ summary: '兼容旧入口:上传 ZIP 并异步解析预览' }) - @ApiConsumes('multipart/form-data') - @UseInterceptors(FileInterceptor('file', { - storage: outboundImportDiskStorage, - limits: { files: 1, fields: 0 }, - })) - import(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) { - return this.outboundService.startImport(file, user.id); - } } diff --git a/apps/api/src/outbound/outbound.module.ts b/apps/api/src/outbound/outbound.module.ts index c52e489..6f62b9f 100644 --- a/apps/api/src/outbound/outbound.module.ts +++ b/apps/api/src/outbound/outbound.module.ts @@ -6,16 +6,26 @@ import { OutboundController } from './outbound.controller'; import { ImportProcessor } from './import.processor'; import { ImportPreviewProcessor } from './import-preview.processor'; import { OutboundImportCleanupService } from './outbound-import-cleanup.service'; +import { BatchOutboundProcessor } from './batch-outbound.processor'; +import { BatchOutboundRecoveryService } from './batch-outbound-recovery.service'; @Module({ imports: [ BullModule.registerQueue( { name: QUEUE_NAMES.IMPORT_OUTBOUND }, { name: QUEUE_NAMES.IMPORT_OUTBOUND_PREVIEW }, + { name: QUEUE_NAMES.BATCH_OUTBOUND }, ), ], controllers: [OutboundController], - providers: [OutboundService, ImportProcessor, ImportPreviewProcessor, OutboundImportCleanupService], + providers: [ + OutboundService, + ImportProcessor, + ImportPreviewProcessor, + OutboundImportCleanupService, + BatchOutboundProcessor, + BatchOutboundRecoveryService, + ], exports: [OutboundService], }) export class OutboundModule {} diff --git a/apps/api/src/outbound/outbound.service.spec.ts b/apps/api/src/outbound/outbound.service.spec.ts index 04166a5..77a8b57 100644 --- a/apps/api/src/outbound/outbound.service.spec.ts +++ b/apps/api/src/outbound/outbound.service.spec.ts @@ -47,22 +47,24 @@ function createHarness(session = readySession()) { $transaction: jest.fn().mockImplementation(async (callback: (client: typeof tx) => unknown) => callback(tx)), }; const storage = { - savePrivateFile: jest.fn().mockResolvedValue({ key: '.private/import.zip' }), + savePrivateFile: jest.fn().mockResolvedValue({ key: '.private/import.zip', size: 3 }), remove: jest.fn().mockResolvedValue(undefined), }; const importQueue = { add: jest.fn().mockResolvedValue(undefined), }; const previewQueue = { add: jest.fn().mockResolvedValue(undefined) }; + const batchQueue = { add: jest.fn().mockResolvedValue(undefined) }; const service = new OutboundService( prisma as any, storage as any, importQueue as any, previewQueue as any, + batchQueue as any, ); const user = { id: 7, role: RoleType.OPERATOR } as any; - return { service, prisma, tx, storage, importQueue, previewQueue, user }; + return { service, prisma, tx, storage, importQueue, previewQueue, batchQueue, user }; } describe('OutboundService.startPreview', () => { @@ -95,7 +97,7 @@ describe('OutboundService.startPreview', () => { }); expect(harness.previewQueue.add).toHaveBeenCalledWith( 'preview', - { jobId: 'preview-job', sessionId: 'preview-session', fileKey: '.private/import.zip' }, + { jobId: 'preview-job', sessionId: 'preview-session', fileKey: '.private/import.zip', fileSize: 3 }, { jobId: 'preview-job' }, ); }); @@ -173,7 +175,7 @@ describe('OutboundService.startPreview', () => { expect(harness.storage.remove).not.toHaveBeenCalled(); expect(harness.previewQueue.add).toHaveBeenCalledWith( 'preview', - { jobId: 'persisted-job', sessionId: 'persisted-session', fileKey: '.private/import.zip' }, + { jobId: 'persisted-job', sessionId: 'persisted-session', fileKey: '.private/import.zip', fileSize: 3 }, { jobId: 'persisted-job' }, ); }); @@ -210,9 +212,9 @@ describe('OutboundService.generateTemplate', () => { const zip = new AdmZip(archive); const names = zip.getEntries().filter((entry) => !entry.isDirectory).map((entry) => entry.entryName).sort(); expect(names).toEqual([ - 'images/out-001.jpg', - 'images/out-002.png', - 'images/out-003.jpg', + 'images/482731000001/out-001.jpg', + 'images/615204000002/out-002.png', + 'images/615204000002/out-003.jpg', 'outbound-import-template.xlsx', '说明.txt', ]); @@ -226,23 +228,27 @@ describe('OutboundService.generateTemplate', () => { undefined, ...OUTBOUND_IMPORT_COLUMNS.map((column) => column.header), ]); - expect(importSheet.getCell('A1').fill).toMatchObject({ fgColor: { argb: 'FF1F4E78' } }); + expect(importSheet.getCell('A1').fill).toMatchObject({ fgColor: { argb: 'FF155E75' } }); expect(importSheet.getCell('A1').font).toMatchObject({ bold: true, color: { argb: 'FFFFFFFF' } }); expect(importSheet.views[0]).toMatchObject({ state: 'frozen', ySplit: 1 }); const exampleSheet = workbook.getWorksheet('填写示例')!; - expect(exampleSheet.getCell('A2').text).toMatch(/^\d{12}$/); - expect(exampleSheet.getCell('D3').text).toContain('images/out-002.png;images/out-003.jpg'); - expect(workbook.getWorksheet('字段说明')?.rowCount).toBe(OUTBOUND_IMPORT_COLUMNS.length + 1); + expect(exampleSheet.rowCount).toBe(3); + expect(exampleSheet.columnCount).toBe(4); + expect(exampleSheet.getCell('A2').text).toBe('482731000001'); + expect(exampleSheet.getCell('A3').text).toBe('615204000002'); + expect(workbook.getWorksheet('字段说明')).toMatchObject({ rowCount: 7, columnCount: 4 }); const instructions = zip.readAsText('说明.txt'); - expect(instructions).toContain('单个 xlsx 最大 100MB'); - expect(instructions).toContain('单张图片最大 100MB'); - expect(instructions).toContain('支持 JPG、JPEG、PNG、WebP;最多 4000 万像素'); - expect(instructions).toContain('不会自动触发区块链上链'); + expect(instructions).toContain('单个 xlsx 不超过 100MB'); + expect(instructions).toContain('单图不超过 100MB'); + expect(instructions).toContain('images/<追溯码>/'); + expect(instructions).toContain('4000 万像素'); + expect(instructions).toContain('最多 10000'); + expect(instructions).toContain('已出库'); - await expect(sharp(zip.readFile('images/out-001.jpg')!).metadata()).resolves.toMatchObject({ format: 'jpeg' }); - await expect(sharp(zip.readFile('images/out-002.png')!).metadata()).resolves.toMatchObject({ format: 'png' }); - await expect(sharp(zip.readFile('images/out-003.jpg')!).metadata()).resolves.toMatchObject({ format: 'jpeg' }); + await expect(sharp(zip.readFile('images/482731000001/out-001.jpg')!).metadata()).resolves.toMatchObject({ format: 'jpeg' }); + await expect(sharp(zip.readFile('images/615204000002/out-002.png')!).metadata()).resolves.toMatchObject({ format: 'png' }); + await expect(sharp(zip.readFile('images/615204000002/out-003.jpg')!).metadata()).resolves.toMatchObject({ format: 'jpeg' }); expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'application/zip'); expect(res.setHeader).toHaveBeenCalledWith('Content-Length', String(archive.length)); }); diff --git a/apps/api/src/outbound/outbound.service.ts b/apps/api/src/outbound/outbound.service.ts index 4e73470..edf6de6 100644 --- a/apps/api/src/outbound/outbound.service.ts +++ b/apps/api/src/outbound/outbound.service.ts @@ -6,9 +6,11 @@ import { readFile, rm } from 'fs/promises'; import { resolve } from 'path'; import { Response } from 'express'; import * as ExcelJS from 'exceljs'; +import sharp from 'sharp'; import { Prisma, RoleType } from '@prisma/client'; import { ErrorCode, + JobItemStatus, JobStatus, JobType, QUEUE_NAMES, @@ -19,10 +21,17 @@ import { BusinessException } from '../common/exceptions/business.exception'; import { buildPage } from '../common/utils/pagination.util'; import { buildOrderBy } from '../common/utils/sort.util'; import { AuthUser } from '../common/decorators/current-user.decorator'; -import { OutboundDto } from './dto/outbound.dto'; +import { BatchOutboundDto, MoveOutboundImageDto, OutboundDto, QueryOutboundImagesDto } from './dto/outbound.dto'; import { QueryImportRowsDto } from './dto/import-session.dto'; -import { isOutbound } from './outbound.util'; -import { OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS } from './outbound-import.util'; +import { + assertOutboundImportDiskCapacity, + OUTBOUND_IMPORT_MAX_IMAGE_PIXELS, + OUTBOUND_IMPORT_MAX_IMAGE_SIZE, + OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS, +} from './outbound-import.util'; +import { + buildTraceCodeSelectionWhere, +} from '../common/utils/trace-code-selection.util'; const SESSION_TTL_DAYS = 2; const OUTBOUND_IMPORT_TEMPLATE_PATH = resolve(__dirname, '..', 'assets', 'templates', 'outbound-import-template.zip'); @@ -54,75 +63,227 @@ export class OutboundService { private readonly storage: StorageService, @InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND) private readonly importQueue: Queue, @InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND_PREVIEW) private readonly previewQueue: Queue, + @InjectQueue(QUEUE_NAMES.BATCH_OUTBOUND) private readonly batchQueue: Queue, ) {} - async updateSingle(traceCodeId: bigint, dto: OutboundDto) { + private mapRecord(record: any) { + if (!record) return null; + return { + ...record, + images: Array.isArray(record.images) ? record.images.map((image: any) => this.mapImage(image)) : undefined, + }; + } + + private mapImage(image: any) { + return { + id: image.id, + key: image.fileKey, + url: this.storage.getUrl(image.fileKey), + name: image.fileName, + type: 'image', + mimeType: image.mimeType, + size: image.size, + width: image.width, + height: image.height, + sortOrder: image.sortOrder, + createdAt: image.createdAt, + }; + } + + async getRecord(traceCodeId: bigint) { const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId }, - include: { artwork: { select: { templateId: true, archiveNo: true } } }, + select: { id: true }, }); if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404); - // 一物一码只能出库一次:已登记出库时间或出库图任一即视为已出库 - if (isOutbound(code)) { - throw new BusinessException(ErrorCode.BAD_REQUEST, '该追溯码已登记出库,不可重复出库'); + const record = await this.prisma.outboundRecord.findUnique({ + where: { traceCodeId }, + include: { _count: { select: { images: true } } }, + }); + if (!record) throw new BusinessException(ErrorCode.NOT_FOUND, '尚未登记出库', 404); + return this.mapRecord(record); + } + + async updateSingle(traceCodeId: bigint, dto: OutboundDto, userId?: number) { + const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId }, select: { id: true } }); + if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404); + const record = await this.prisma.outboundRecord.upsert({ + where: { traceCodeId }, + create: { + traceCodeId, + outTime: new Date(dto.outTime), + remark: dto.remark?.trim() || null, + createdBy: userId, + updatedBy: userId, + }, + update: { + outTime: new Date(dto.outTime), + remark: dto.remark?.trim() || null, + updatedBy: userId, + }, + include: { _count: { select: { images: true } } }, + }); + return this.mapRecord(record); + } + + async createBatchJob(dto: BatchOutboundDto, userId: number) { + const selectionCutoff = new Date(); + const { where, orderedIds } = buildTraceCodeSelectionWhere(dto.selection); + const snapshotMaxId = orderedIds + ? null + : (await this.prisma.traceCode.aggregate({ where, _max: { id: true } }))._max.id; + if (!orderedIds && !snapshotMaxId) throw new BusinessException(ErrorCode.BAD_REQUEST, '没有可处理的追溯码'); + const payload = { + outTime: new Date(dto.outTime).toISOString(), + remark: dto.remark?.trim() || null, + selection: dto.selection as unknown as Prisma.InputJsonValue, + selectionCutoff: selectionCutoff.toISOString(), + snapshotMaxId: snapshotMaxId?.toString() ?? null, + preparing: true, + }; + const created = await this.prisma.job.create({ + data: { + type: JobType.BATCH_OUTBOUND, + status: JobStatus.PENDING, + total: orderedIds?.length ?? 0, + createdBy: userId, + payload, + }, + }); + await this.batchQueue + .add('batch-outbound', { jobId: created.id }, { jobId: `batch-outbound-${created.id}` }) + .catch((error) => this.logger.warn(`批量出库任务等待恢复入队:${created.id} ${(error as Error).message}`)); + return { jobId: created.id, total: created.total }; + } + + async listImages(traceCodeId: bigint, query: QueryOutboundImagesDto) { + const record = await this.prisma.outboundRecord.findUnique({ where: { traceCodeId }, select: { id: true } }); + if (!record) return { items: [], total: 0, page: query.page, pageSize: query.pageSize }; + const [items, total] = await this.prisma.$transaction([ + this.prisma.outboundImage.findMany({ + where: { outboundRecordId: record.id }, + orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }], + skip: (query.page - 1) * query.pageSize, + take: query.pageSize, + }), + this.prisma.outboundImage.count({ where: { outboundRecordId: record.id } }), + ]); + return { items: items.map((image) => this.mapImage(image)), total, page: query.page, pageSize: query.pageSize }; + } + + async uploadImage(traceCodeId: bigint, file: Express.Multer.File, userId?: number) { + if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请选择出库实况图'); + if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.mimetype)) { + throw new BusinessException(ErrorCode.FILE_TYPE_NOT_ALLOWED, `不支持的图片类型:${file.mimetype}`); } - // 出库时间必填:出库登记必须有出库时间 - if (!dto.outTime) { - throw new BusinessException(ErrorCode.BAD_REQUEST, '出库时间不能为空'); + if (file.size > OUTBOUND_IMPORT_MAX_IMAGE_SIZE) { + throw new BusinessException(ErrorCode.FILE_TOO_LARGE, '单张图片不能超过 100MB'); } - const imageKeys = dto.outImageKeys ?? (dto.outImageKey ? [dto.outImageKey] : []); - const data: Prisma.TraceCodeUpdateManyMutationInput = {}; - const relocatedKeys: string[] = []; - data.outTime = new Date(dto.outTime); - if ('outImageKeys' in dto || 'outImageKey' in dto) { - let imageItems = imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' })); - // 出库实况图归位到 {模板ID}/{档案编号}/{追溯码}/出库实况_{时间戳}_{序号} - if (imageItems.length && code.artwork?.archiveNo) { - const dir = `${code.artwork.templateId}/${code.artwork.archiveNo}/${code.shortCode}`; - const relocated = await this.storage.relocateMedia(imageItems, dir, '出库实况'); - relocatedKeys.push(...relocated.keyMap.values()); - imageItems = relocated.items.map((item) => ({ - ...item, - name: item.key.split('/').pop() || item.name, - })); - } - // 无图时写 DB NULL(而非 JSON null),保证出库状态筛选一致 - data.outImages = imageItems.length ? imageItems : Prisma.DbNull; - } - if ('remark' in dto) data.remark = dto.remark || null; - let duplicateDetected = false; + let metadata: sharp.Metadata; try { - const updated = await this.prisma.traceCode.updateMany({ - where: { id: traceCodeId, outTime: null }, - data, + metadata = await sharp(file.path, { limitInputPixels: OUTBOUND_IMPORT_MAX_IMAGE_PIXELS }).metadata(); + } catch { + throw new BusinessException(ErrorCode.BAD_REQUEST, '图片内容无效或像素超过 4000 万'); + } + const expected = file.mimetype === 'image/png' ? 'png' : file.mimetype === 'image/webp' ? 'webp' : 'jpeg'; + if (metadata.format !== expected || !metadata.width || !metadata.height || (metadata.pages ?? 1) > 1) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '图片实际格式与扩展名不一致或不支持多帧图片'); + } + if (metadata.width * metadata.height > OUTBOUND_IMPORT_MAX_IMAGE_PIXELS) { + throw new BusinessException(ErrorCode.BAD_REQUEST, '图片像素不能超过 4000 万'); + } + const code = await this.prisma.traceCode.findUnique({ + where: { id: traceCodeId }, + include: { + outbound: { select: { id: true } }, + artwork: { select: { templateId: true, archiveNo: true } }, + }, + }); + if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404); + if (!code.outbound) throw new BusinessException(ErrorCode.BAD_REQUEST, '请先登记出库时间,再补录实况图'); + const saved = await this.storage.saveFile(file.path, file.originalname, file.mimetype); + const dir = `${code.artwork.templateId}/${code.artwork.archiveNo || '未归档'}/${code.shortCode}`; + let finalKey = saved.key; + try { + const relocated = await this.storage.relocateMedia([{ key: saved.key }], dir, '出库实况'); + finalKey = relocated.items[0]?.key || saved.key; + const image = await this.prisma.$transaction(async (tx) => { + const created = await tx.outboundImage.create({ + data: { + outboundRecordId: code.outbound!.id, + fileKey: finalKey, + fileName: file.originalname.slice(0, 191), + mimeType: file.mimetype, + size: BigInt(file.size), + width: metadata.width!, + height: metadata.height!, + sortOrder: 0, + createdBy: userId, + }, + }); + // 全局自增 ID 同时作为稳定顺序,避免并发上传读取同一个 count 后产生重复排序值。 + return tx.outboundImage.update({ + where: { id: created.id }, + data: { sortOrder: Number(created.id) }, + }); }); - if (updated.count !== 1) { - duplicateDetected = true; - throw new BusinessException(ErrorCode.BAD_REQUEST, '该追溯码已登记出库,不可重复出库'); - } - return this.prisma.traceCode.findUniqueOrThrow({ where: { id: traceCodeId } }); + return this.mapImage(image); } catch (error) { - let committedWithRelocatedImages = false; - let commitStateKnown = false; - if (relocatedKeys.length && !duplicateDetected) { - try { - const current = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId }, select: { outImages: true } }); - const currentKeys = Array.isArray(current?.outImages) - ? current.outImages.map((item: any) => String(item?.key || '')).filter(Boolean) - : []; - committedWithRelocatedImages = relocatedKeys.every((key) => currentKeys.includes(key)); - commitStateKnown = true; - } catch { - // 提交结果未知时保留文件,宁可留待清理也不能删除可能已经入库的业务图片。 - } - } - if (duplicateDetected || (commitStateKnown && !committedWithRelocatedImages)) { - for (const key of relocatedKeys) await this.storage.remove(key).catch(() => undefined); - } + await this.storage.remove(finalKey).catch(() => undefined); throw error; } } + async deleteImage(traceCodeId: bigint, imageId: bigint) { + const image = await this.prisma.outboundImage.findFirst({ + where: { id: imageId, outboundRecord: { traceCodeId } }, + }); + if (!image) throw new BusinessException(ErrorCode.NOT_FOUND, '出库实况图不存在', 404); + await this.storage.remove(image.fileKey); + await this.prisma.outboundImage.deleteMany({ where: { id: image.id, fileKey: image.fileKey } }); + return { success: true }; + } + + async moveImage(traceCodeId: bigint, imageId: bigint, dto: MoveOutboundImageDto) { + for (let attempt = 0; attempt < 3; attempt += 1) { + try { + return await this.prisma.$transaction(async (tx) => { + const current = await tx.outboundImage.findFirst({ + where: { id: imageId, outboundRecord: { traceCodeId } }, + }); + if (!current) throw new BusinessException(ErrorCode.NOT_FOUND, '出库实况图不存在', 404); + const previous = dto.direction === 'UP'; + const neighbor = await tx.outboundImage.findFirst({ + where: { + outboundRecordId: current.outboundRecordId, + OR: previous + ? [{ sortOrder: { lt: current.sortOrder } }, { sortOrder: current.sortOrder, id: { lt: current.id } }] + : [{ sortOrder: { gt: current.sortOrder } }, { sortOrder: current.sortOrder, id: { gt: current.id } }], + }, + orderBy: previous + ? [{ sortOrder: 'desc' }, { id: 'desc' }] + : [{ sortOrder: 'asc' }, { id: 'asc' }], + }); + if (!neighbor) return { success: true, moved: false }; + if (neighbor.sortOrder === current.sortOrder) throw new Error('OUTBOUND_IMAGE_ORDER_CONFLICT'); + const moved = await tx.outboundImage.updateMany({ + where: { id: current.id, sortOrder: current.sortOrder }, + data: { sortOrder: neighbor.sortOrder }, + }); + const swapped = await tx.outboundImage.updateMany({ + where: { id: neighbor.id, sortOrder: neighbor.sortOrder }, + data: { sortOrder: current.sortOrder }, + }); + if (moved.count !== 1 || swapped.count !== 1) throw new Error('OUTBOUND_IMAGE_ORDER_CONFLICT'); + return { success: true, moved: true }; + }); + } catch (error) { + if ((error as Error).message !== 'OUTBOUND_IMAGE_ORDER_CONFLICT') throw error; + } + } + throw new BusinessException(ErrorCode.BAD_REQUEST, '图片顺序已变化,请刷新后重试', 409); + } + async generateTemplate(res: Response): Promise { let archive: Buffer; try { @@ -170,13 +331,14 @@ export class OutboundService { const fileSize = file.size || 0; if (!fileSize) throw new BusinessException(ErrorCode.BAD_REQUEST, '导入 ZIP 文件不能为空'); if (!file.path) throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入 ZIP 临时文件不存在'); + await assertOutboundImportDiskCapacity(fileSize, 2); const saved = await this.storage.savePrivateFile( file.path, file.originalname || 'outbound-import.zip', 'application/zip', { requestTimeoutMs: OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS }, ); - let created: { sessionId: string; jobId: string; fileKey: string }; + let created: { sessionId: string; jobId: string; fileKey: string; fileSize: number }; try { created = await this.prisma.$transaction(async (tx) => { const session = await tx.outboundImportSession.create({ @@ -193,14 +355,14 @@ export class OutboundService { type: JobType.IMPORT_OUTBOUND_PREVIEW, status: JobStatus.PENDING, createdBy: userId, - payload: { sessionId: session.id, fileKey: saved.key }, + payload: { sessionId: session.id, fileKey: saved.key, fileSize: saved.size }, }, }); await tx.outboundImportSession.update({ where: { id: session.id }, data: { previewJobId: previewJob.id }, }); - return { sessionId: session.id, jobId: previewJob.id, fileKey: saved.key }; + return { sessionId: session.id, jobId: previewJob.id, fileKey: saved.key, fileSize: saved.size }; }); } catch (error) { let persistedByFile: Awaited> | null | undefined; @@ -216,6 +378,7 @@ export class OutboundService { sessionId: persistedByFile.id, jobId: persistedByFile.previewJobId, fileKey: persistedByFile.fileKey, + fileSize: saved.size, }; } else { const existing = normalizedRequestId @@ -227,7 +390,12 @@ export class OutboundService { await this.storage.remove(saved.key).catch(() => undefined); } if (existing?.createdBy === userId && existing.previewJobId && existing.fileKey) { - created = { sessionId: existing.id, jobId: existing.previewJobId, fileKey: existing.fileKey }; + created = { + sessionId: existing.id, + jobId: existing.previewJobId, + fileKey: existing.fileKey, + fileSize: saved.size, + }; } else { this.logger.error(`创建出库导入预览记录失败:${(error as Error).message}`); throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入预览任务创建失败,请稍后重试'); @@ -238,7 +406,12 @@ export class OutboundService { try { await this.previewQueue.add( 'preview', - { jobId: created.jobId, sessionId: created.sessionId, fileKey: created.fileKey }, + { + jobId: created.jobId, + sessionId: created.sessionId, + fileKey: created.fileKey, + fileSize: created.fileSize, + }, { jobId: created.jobId }, ); } catch (error) { @@ -247,10 +420,6 @@ export class OutboundService { return { sessionId: created.sessionId, jobId: created.jobId }; } - startImport(file: Express.Multer.File, userId: number) { - return this.startPreview(file, userId); - } - private async requireSession(id: string, user: AuthUser) { const session = await this.prisma.outboundImportSession.findUnique({ where: { id } }); if (!session) throw new BusinessException(ErrorCode.NOT_FOUND, '导入会话不存在', 404); diff --git a/apps/api/src/outbound/outbound.util.ts b/apps/api/src/outbound/outbound.util.ts index 57b9a5a..4792191 100644 --- a/apps/api/src/outbound/outbound.util.ts +++ b/apps/api/src/outbound/outbound.util.ts @@ -1,6 +1,3 @@ -// 判定追溯码是否已出库:登记了出库时间或出库实况图任一即视为已出库。 -// 新登记强制填写出库时间;仍识别历史上仅有图片的数据,避免升级后被重复出库。 -export function isOutbound(code: { outTime?: Date | null; outImages?: unknown }): boolean { - if (code.outTime) return true; - return Array.isArray(code.outImages) && code.outImages.length > 0; +export function isOutbound(code: { outbound?: unknown }): boolean { + return Boolean(code.outbound); } diff --git a/apps/api/src/public-trace/public-trace.controller.ts b/apps/api/src/public-trace/public-trace.controller.ts index 0840f31..849a87e 100644 --- a/apps/api/src/public-trace/public-trace.controller.ts +++ b/apps/api/src/public-trace/public-trace.controller.ts @@ -3,12 +3,33 @@ import { Request, Response } from 'express'; import { ApiOperation, ApiTags } from '@nestjs/swagger'; import { Throttle } from '@nestjs/throttler'; import { ConfigService } from '@nestjs/config'; +import { Type } from 'class-transformer'; +import { IsInt, IsOptional, IsString, Max, Min } from 'class-validator'; import { Public } from '../common/decorators/public.decorator'; import { extractIp } from '../common/utils/ua.util'; import { isValidPreviewToken } from '../common/utils/preview-token.util'; import { PublicTraceService } from './public-trace.service'; import { SettingsService } from '../settings/settings.service'; +class QueryPublicOutboundImagesDto { + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + page = 1; + + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + @Max(100) + pageSize = 20; + + @IsOptional() + @IsString() + token?: string; +} + @ApiTags('公开溯源') @Controller() export class PublicTraceController { @@ -45,6 +66,20 @@ export class PublicTraceController { return this.service.preview(shortCode, state === 'active' ? 'active' : 'inactive'); } + @Public() + @Get('public/trace/:shortCode/outbound-images') + @Throttle({ default: { limit: 60, ttl: 60_000 } }) + @ApiOperation({ summary: '分页查询公开出库实况图' }) + outboundImages( + @Param('shortCode') shortCode: string, + @Query() query: QueryPublicOutboundImagesDto, + ) { + const previewRequested = Boolean(query.token); + const previewAuthorized = previewRequested && isValidPreviewToken(this.config.get('jwt.secret') || '', query.token); + if (previewRequested && !previewAuthorized) return { status: 'PREVIEW_EXPIRED' as const }; + return this.service.outboundImages(shortCode, query.page, query.pageSize, previewAuthorized); + } + // 短链跳转:扫码打开 /t/:shortCode -> 重定向到 C 端溯源页(不在 /api 前缀下) @Public() @Get('t/:shortCode') diff --git a/apps/api/src/public-trace/public-trace.service.spec.ts b/apps/api/src/public-trace/public-trace.service.spec.ts new file mode 100644 index 0000000..9637cd5 --- /dev/null +++ b/apps/api/src/public-trace/public-trace.service.spec.ts @@ -0,0 +1,78 @@ +import { ArtworkStatus, AuditStatus, TraceCodeStatus } from '@artveris/shared'; +import { PublicTraceService } from './public-trace.service'; + +function createHarness() { + const code = { + id: 1n, + shortCode: '482731000001', + artworkId: 10, + status: TraceCodeStatus.INACTIVE, + queryCount: 0, + firstActivatedAt: null, + lastQueriedAt: null, + batch: { batchNo: 'B1' }, + artwork: { + id: 10, + archiveNo: 'A1', + status: ArtworkStatus.DRAFT, + auditStatus: AuditStatus.APPROVED, + deletedAt: null, + }, + outbound: null, + }; + const artwork = { + ...code.artwork, + title: '草稿作品', + artist: null, + images: [], + dynamicFields: null, + template: { fields: [] }, + traceNodes: [], + certificates: [], + }; + const prisma = { + traceCode: { + findUnique: jest.fn().mockImplementation(async ({ select }: any) => { + if (select && Object.keys(select).length === 1 && select.id) return { id: code.id }; + return code; + }), + updateMany: jest.fn(), + update: jest.fn(), + }, + artwork: { findFirst: jest.fn().mockResolvedValue(artwork) }, + queryLog: { create: jest.fn().mockResolvedValue({}) }, + blockchainProof: { findUnique: jest.fn() }, + outboundImage: { findMany: jest.fn(), count: jest.fn() }, + $transaction: jest.fn(), + }; + const redis = { + get: jest.fn().mockResolvedValue(null), + set: jest.fn().mockResolvedValue('OK'), + }; + const storage = { getUrl: jest.fn((key: string) => `/uploads/${key}`) }; + const settings = { getAllRaw: jest.fn().mockResolvedValue({}) }; + const service = new PublicTraceService(prisma as any, storage as any, settings as any, redis as any); + return { service, prisma }; +} + +describe('PublicTraceService draft visibility', () => { + it('returns INVALID for a draft artwork even when it is approved', async () => { + const { service, prisma } = createHarness(); + + await expect(service.trace('482731000001', { ip: '127.0.0.1' })).resolves.toEqual({ status: 'INVALID' }); + expect(prisma.traceCode.updateMany).not.toHaveBeenCalled(); + }); + + it('does not expose an approved draft through preview', async () => { + const { service } = createHarness(); + + await expect(service.preview('482731000001', 'inactive')).resolves.toEqual({ status: 'INVALID' }); + }); + + it('does not expose outbound images for an approved draft', async () => { + const { service, prisma } = createHarness(); + + await expect(service.outboundImages('482731000001', 1, 20, true)).resolves.toEqual({ status: 'INVALID' }); + expect(prisma.outboundImage.findMany).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/src/public-trace/public-trace.service.ts b/apps/api/src/public-trace/public-trace.service.ts index ef6a4aa..a1c5f84 100644 --- a/apps/api/src/public-trace/public-trace.service.ts +++ b/apps/api/src/public-trace/public-trace.service.ts @@ -54,7 +54,10 @@ export class PublicTraceService { description: string | null; mediaFiles: unknown; }>, - code: { outTime?: Date | null; outImages?: unknown }, + outbound: { + outTime: Date; + images: Array<{ fileKey: string; fileName: string; mimeType: string; id: bigint; size: bigint; width: number; height: number; sortOrder: number }>; + } | null, ) { const timeline = nodes.map((n) => ({ nodeType: n.nodeType, @@ -66,20 +69,15 @@ export class PublicTraceService { media: this.mapMedia(n.mediaFiles), })); - const outMedia = Array.isArray(code.outImages) - ? (code.outImages as Array<{ key?: string; name?: string; type?: string }>) - .map((item) => (typeof item === 'string' ? { key: item } : item)) - .filter((item) => item?.key) - .map((item) => ({ name: item.name || '出库实况图', type: item.type || 'image', url: this.storage.getUrl(item.key as string) })) - : []; + const outMedia = outbound?.images.map((image) => this.mapOutboundImage(image)) ?? []; - if (code.outTime || outMedia.length) { + if (outbound) { // 单件出库记录:不下发中文标题/说明,标记 system=OUTBOUND_RECORD 由 C 端按语言本地化 timeline.push({ nodeType: 'OUTBOUND', system: 'OUTBOUND_RECORD', title: null, - occurredAt: code.outTime ?? null, + occurredAt: outbound.outTime, location: null, description: null, media: outMedia, @@ -89,6 +87,30 @@ export class PublicTraceService { return timeline; } + private mapOutboundImage(image: { + id: bigint; + fileKey: string; + fileName: string; + mimeType: string; + size: bigint; + width: number; + height: number; + sortOrder: number; + }) { + return { + id: image.id, + key: image.fileKey, + url: this.storage.getUrl(image.fileKey), + name: image.fileName, + type: 'image', + mimeType: image.mimeType, + size: image.size, + width: image.width, + height: image.height, + sortOrder: image.sortOrder, + }; + } + private async resolveId(shortCode: string): Promise { const cacheKey = `trace:map:${shortCode}`; const cached = await this.redis.get(cacheKey); @@ -120,7 +142,16 @@ export class PublicTraceService { const code = await this.prisma.traceCode.findUnique({ where: { id }, - include: { batch: true, artwork: true }, + include: { + batch: true, + artwork: true, + outbound: { + include: { + images: { orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }], take: 20 }, + _count: { select: { images: true } }, + }, + }, + }, }); if (!code) { await this.writeLog(id, null, shortCode, QueryResult.INVALID, ctx); @@ -146,7 +177,7 @@ export class PublicTraceService { // 仅展示「未停用」且「审核通过」的作品,否则视为无效,避免未审核数据外泄 if ( !artwork || - artwork.status === ArtworkStatus.DISABLED || + artwork.status !== ArtworkStatus.ACTIVE || artwork.auditStatus !== AuditStatus.APPROVED ) { await this.writeLog(id, code.artworkId, shortCode, QueryResult.INVALID, ctx, code); @@ -179,10 +210,7 @@ export class PublicTraceService { // 回查最新值组装响应(首次激活时读到自身写入,重复查询读到自增后的值) const updated = await this.prisma.traceCode.findUniqueOrThrow({ where: { id } }); - const proof = await this.prisma.blockchainProof.findFirst({ - where: { traceCodeId: id, status: ProofStatus.ONCHAIN }, - orderBy: { id: 'desc' }, - }); + const proof = await this.prisma.blockchainProof.findUnique({ where: { traceCodeId: id } }); const result = firstActivate ? QueryResult.FIRST_ACTIVATE : QueryResult.REPEAT; await this.writeLog(id, artwork.id, shortCode, result, ctx, { ...code, ...updated }); @@ -209,7 +237,16 @@ export class PublicTraceService { const code = await this.prisma.traceCode.findUnique({ where: { id }, - include: { batch: true, artwork: true }, + include: { + batch: true, + artwork: true, + outbound: { + include: { + images: { orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }], take: 20 }, + _count: { select: { images: true } }, + }, + }, + }, }); if (!code) return { status: 'INVALID' as const }; if (code.status === TraceCodeStatus.DISABLED) return { status: 'DISABLED' as const }; @@ -225,16 +262,13 @@ export class PublicTraceService { }); if ( !artwork || - artwork.status === ArtworkStatus.DISABLED || + artwork.status !== ArtworkStatus.ACTIVE || artwork.auditStatus !== AuditStatus.APPROVED ) { return { status: 'INVALID' as const }; } - const proof = await this.prisma.blockchainProof.findFirst({ - where: { traceCodeId: id, status: ProofStatus.ONCHAIN }, - orderBy: { id: 'desc' }, - }); + const proof = await this.prisma.blockchainProof.findUnique({ where: { traceCodeId: id } }); const now = new Date(); const firstQuery = state === 'inactive'; @@ -257,17 +291,25 @@ export class PublicTraceService { // trace/preview 共用的作品展示数据(作品信息 / 时间线 / 证书 / 区块链存证) private buildArtworkPayload( artwork: ArtworkWithRel, - code: { outTime?: Date | null; outImages?: unknown }, + code: { + outbound?: { + outTime: Date; + remark: string | null; + images: Array<{ id: bigint; fileKey: string; fileName: string; mimeType: string; size: bigint; width: number; height: number; sortOrder: number }>; + _count: { images: number }; + } | null; + }, proof: { txHash: string | null; - dataHash: string; blockHash: string | null; blockHeight: bigint | null; chainName: string | null; onchainAt: Date | null; explorerUrl: string | null; - tokenId: bigint | null; contractAddress: string | null; + status: string; + failureReason: string | null; + submittedAt: Date | null; } | null, explorerUrl: string | null, ) { @@ -279,7 +321,20 @@ export class PublicTraceService { images: this.mapMedia(artwork.images), fields: this.buildFields(artwork.template.fields, artwork.dynamicFields), }, - timeline: this.buildTimeline(artwork.traceNodes, code), + timeline: this.buildTimeline(artwork.traceNodes, code.outbound ?? null), + outbound: code.outbound + ? { + outTime: code.outbound.outTime, + remark: code.outbound.remark, + images: { + items: code.outbound.images.map((image) => this.mapOutboundImage(image)), + total: code.outbound._count.images, + page: 1, + pageSize: 20, + hasMore: code.outbound._count.images > code.outbound.images.length, + }, + } + : null, certificates: artwork.certificates.map((c) => ({ name: c.name, issuer: c.issuer, @@ -288,21 +343,70 @@ export class PublicTraceService { url: c.watermarkFileUrl ? this.storage.getUrl(c.watermarkFileUrl) : null, })), blockchain: proof - ? { + ? { + status: proof.status, txHash: proof.txHash, - dataHash: proof.dataHash, blockHash: proof.blockHash, blockHeight: proof.blockHeight, chainName: proof.chainName, onchainAt: proof.onchainAt, explorerUrl, - tokenId: proof.tokenId, contractAddress: proof.contractAddress, + submittedAt: proof.submittedAt, + failureReason: this.publicFailureReason(proof.status, proof.failureReason), } : null, }; } + private publicFailureReason(status: string, reason: string | null): string | null { + if (status === ProofStatus.UNKNOWN) return '链上结果暂时无法确认,请稍后重试或联系平台管理员'; + if (status === ProofStatus.FAILED) return reason ? '上链处理失败,请联系平台管理员' : '上链处理失败'; + return null; + } + + async outboundImages(shortCode: string, page: number, pageSize: number, previewAuthorized: boolean) { + if (!TRACE_CODE_PATTERN.test(shortCode)) return { status: 'INVALID' as const }; + const id = await this.resolveId(shortCode); + if (id === null) return { status: 'INVALID' as const }; + const code = await this.prisma.traceCode.findUnique({ + where: { id }, + select: { + status: true, + artwork: { select: { status: true, auditStatus: true, deletedAt: true } }, + outbound: { select: { id: true } }, + }, + }); + if ( + !code || + (!previewAuthorized && code.status !== TraceCodeStatus.ACTIVE) || + code.status === TraceCodeStatus.DISABLED || + code.status === TraceCodeStatus.ABNORMAL || + code.artwork.deletedAt || + code.artwork.status !== ArtworkStatus.ACTIVE || + code.artwork.auditStatus !== AuditStatus.APPROVED + ) { + return { status: 'INVALID' as const }; + } + if (!code.outbound) return { items: [], total: 0, page, pageSize, hasMore: false }; + const [items, total] = await this.prisma.$transaction([ + this.prisma.outboundImage.findMany({ + where: { outboundRecordId: code.outbound.id }, + orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }], + skip: (page - 1) * pageSize, + take: pageSize, + }), + this.prisma.outboundImage.count({ where: { outboundRecordId: code.outbound.id } }), + ]); + return { + items: items.map((image) => this.mapOutboundImage(image)), + total, + page, + pageSize, + hasMore: page * pageSize < total, + }; + } + private async resolveExplorerUrl( proof: { txHash: string | null; chainName: string | null; explorerUrl: string | null } | null, ): Promise { diff --git a/apps/api/src/storage/local.driver.spec.ts b/apps/api/src/storage/local.driver.spec.ts index facc77d..a94b59c 100644 --- a/apps/api/src/storage/local.driver.spec.ts +++ b/apps/api/src/storage/local.driver.spec.ts @@ -63,4 +63,15 @@ describe('LocalDriver', () => { await expect(driver.get('temp/source.jpg')).resolves.toEqual(Buffer.from('image')); await expect(driver.get('final/copied.jpg')).resolves.toEqual(Buffer.from('image')); }); + + it('lists only keys under the requested preview prefix', async () => { + const driver = createDriver(); + await driver.put('outbound-preview/session-1/first.jpg', Buffer.from('first')); + await driver.put('outbound-preview/session-2/second.jpg', Buffer.from('second')); + await driver.put('archive/kept.jpg', Buffer.from('kept')); + + await expect(driver.list('outbound-preview/session-1/')).resolves.toEqual([ + 'outbound-preview/session-1/first.jpg', + ]); + }); }); diff --git a/apps/api/src/storage/local.driver.ts b/apps/api/src/storage/local.driver.ts index 190a345..4bacf26 100644 --- a/apps/api/src/storage/local.driver.ts +++ b/apps/api/src/storage/local.driver.ts @@ -57,7 +57,7 @@ export class LocalDriver implements StorageDriver { await rm(this.fullPath(key), { force: true }); } - async list(): Promise { + async list(prefix = ''): Promise { if (!existsSync(this.root)) return []; const keys: string[] = []; const walk = async (dir: string): Promise => { @@ -71,7 +71,7 @@ export class LocalDriver implements StorageDriver { } }; await walk(this.root); - return keys; + return prefix ? keys.filter((key) => key.startsWith(prefix)) : keys; } private getPublicPrefix(): string { diff --git a/apps/api/src/storage/oss.driver.spec.ts b/apps/api/src/storage/oss.driver.spec.ts index dbce2bc..919aea8 100644 --- a/apps/api/src/storage/oss.driver.spec.ts +++ b/apps/api/src/storage/oss.driver.spec.ts @@ -120,4 +120,21 @@ describe('OssDriver request timeout', () => { ContentType: 'image/jpeg', }); }); + + it('passes the preview-session prefix to object listing', async () => { + const driver = createDriver(); + const send = jest.fn().mockResolvedValue({ + Contents: [{ Key: 'outbound-preview/session-1/first.jpg' }], + }); + (driver as any).client.send = send; + + await expect(driver.list('outbound-preview/session-1/')).resolves.toEqual([ + 'outbound-preview/session-1/first.jpg', + ]); + + expect(send.mock.calls[0][0].input).toMatchObject({ + Bucket: 'artveris', + Prefix: 'outbound-preview/session-1/', + }); + }); }); diff --git a/apps/api/src/storage/oss.driver.ts b/apps/api/src/storage/oss.driver.ts index 2423c2e..d9f140a 100644 --- a/apps/api/src/storage/oss.driver.ts +++ b/apps/api/src/storage/oss.driver.ts @@ -131,12 +131,12 @@ export class OssDriver implements StorageDriver { )); } - async list(): Promise { + async list(prefix = ''): Promise { const keys: string[] = []; let token: string | undefined; do { const res = await this.withRequestTimeout((abortSignal) => this.client.send( - new ListObjectsV2Command({ Bucket: this.opts.bucket, ContinuationToken: token }), + new ListObjectsV2Command({ Bucket: this.opts.bucket, ContinuationToken: token, Prefix: prefix || undefined }), { abortSignal }, )); for (const item of res.Contents || []) { diff --git a/apps/api/src/storage/storage.service.spec.ts b/apps/api/src/storage/storage.service.spec.ts index 0b0d3c4..8b0c14e 100644 --- a/apps/api/src/storage/storage.service.spec.ts +++ b/apps/api/src/storage/storage.service.spec.ts @@ -163,6 +163,43 @@ describe('StorageService.savePrivate', () => { expect.objectContaining({ contentType: 'image/webp', visibility: 'public' }), ); }); + + it('restores a storage key from disk without loading the file into a Buffer', async () => { + const { service, driver } = createHarness(); + const dir = await mkdtemp(join(tmpdir(), 'artveris-storage-restore-test-')); + const filePath = join(dir, 'photo.webp'); + await writeFile(filePath, Buffer.from('image')); + try { + await service.putKeyFile('archive/photo.webp', filePath); + + expect(driver.putFile).toHaveBeenCalledWith( + 'archive/photo.webp', + filePath, + 5, + expect.objectContaining({ contentType: 'image/webp', visibility: 'public' }), + ); + expect(driver.put).not.toHaveBeenCalled(); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); + + it('uses a caller timeout when overwriting a deterministic preview key', async () => { + const { service, driver } = createHarness(); + const key = 'outbound-preview/session-1/path-hash.jpg'; + + await service.putKey(key, Buffer.from('image'), 'image/jpeg', { requestTimeoutMs: 3_600_000 }); + + expect(driver.put).toHaveBeenCalledWith( + key, + expect.any(Buffer), + expect.objectContaining({ + cacheControl: 'public, max-age=31536000, immutable', + visibility: 'public', + requestTimeoutMs: 3_600_000, + }), + ); + }); }); describe('StorageService.relocateMedia', () => { diff --git a/apps/api/src/storage/storage.service.ts b/apps/api/src/storage/storage.service.ts index 734e096..996f95e 100644 --- a/apps/api/src/storage/storage.service.ts +++ b/apps/api/src/storage/storage.service.ts @@ -256,13 +256,65 @@ export class StorageService implements OnModuleInit { }; } - async putKey(key: string, buffer: Buffer, mime?: string): Promise { + async saveFile( + filePath: string, + originalName: string, + mime?: string, + requestOptions: StorageRequestOptions = {}, + ): Promise { + const file = await stat(filePath); + const hash = await this.buildFileHash(filePath); + const key = this.buildKey(originalName, hash, mime); + const url = await this.withDriverOperation(async (driver) => { + await driver.putFile(key, filePath, file.size, { + contentType: mime || storageContentType(key), + cacheControl: STATIC_ASSET_CACHE_CONTROL, + ...requestOptions, + }); + return driver.getPublicUrl(key); + }); + return { + key, + url, + name: originalName, + size: file.size, + mime: mime || 'application/octet-stream', + hash, + }; + } + + async putKey( + key: string, + buffer: Buffer, + mime?: string, + requestOptions: StorageRequestOptions = {}, + ): Promise { const isPrivate = key.startsWith('.private/'); return this.withDriverOperation(async (driver) => { await driver.put(key, buffer, { contentType: mime || storageContentType(key), cacheControl: isPrivate ? 'private, no-store' : STATIC_ASSET_CACHE_CONTROL, visibility: isPrivate ? 'private' : 'public', + ...requestOptions, + }); + return isPrivate ? '' : driver.getPublicUrl(key); + }); + } + + async putKeyFile( + key: string, + filePath: string, + mime?: string, + requestOptions: StorageRequestOptions = {}, + ): Promise { + const file = await stat(filePath); + const isPrivate = key.startsWith('.private/'); + return this.withDriverOperation(async (driver) => { + await driver.putFile(key, filePath, file.size, { + contentType: mime || storageContentType(key), + cacheControl: isPrivate ? 'private, no-store' : STATIC_ASSET_CACHE_CONTROL, + visibility: isPrivate ? 'private' : 'public', + ...requestOptions, }); return isPrivate ? '' : driver.getPublicUrl(key); }); @@ -410,8 +462,8 @@ export class StorageService implements OnModuleInit { await this.withDriverOperation((driver) => driver.remove(key)); } - async listKeys(): Promise { - return this.withDriverOperation((driver) => driver.list ? driver.list() : Promise.resolve([])); + async listKeys(prefix = ''): Promise { + return this.withDriverOperation((driver) => driver.list ? driver.list(prefix) : Promise.resolve([])); } async test(driver: StorageDriver): Promise { diff --git a/apps/api/src/storage/storage.types.ts b/apps/api/src/storage/storage.types.ts index f97bd4e..407d11f 100644 --- a/apps/api/src/storage/storage.types.ts +++ b/apps/api/src/storage/storage.types.ts @@ -16,7 +16,7 @@ export interface StorageDriver { getFile(key: string, filePath: string, options?: StorageRequestOptions): Promise; remove(key: string): Promise; getPublicUrl(key: string): string; - list?(): Promise; + list?(prefix?: string): Promise; } export interface SavedFile { diff --git a/apps/api/src/trace-code/dto/trace-code.dto.ts b/apps/api/src/trace-code/dto/trace-code.dto.ts index c613fb3..77cf313 100644 --- a/apps/api/src/trace-code/dto/trace-code.dto.ts +++ b/apps/api/src/trace-code/dto/trace-code.dto.ts @@ -1,5 +1,5 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; -import { Type } from 'class-transformer'; +import { Transform, Type } from 'class-transformer'; import { ArrayNotEmpty, IsArray, @@ -15,6 +15,7 @@ import { } from 'class-validator'; import { TraceCodeStatus } from '@artveris/shared'; import { PaginationDto } from '../../common/dto/pagination.dto'; +import { ONCHAIN_FILTER_STATUSES, OnchainFilterStatus } from '../../common/dto/trace-code-selection.dto'; export class GenerateBatchDto { @ApiProperty({ description: '所属作品(款)ID' }) @@ -65,6 +66,19 @@ export class QueryTraceCodeDto extends PaginationDto { @IsIn(['OUTBOUND', 'NOT_OUTBOUND']) outboundStatus?: 'OUTBOUND' | 'NOT_OUTBOUND'; + @ApiPropertyOptional({ description: '上链状态', enum: ONCHAIN_FILTER_STATUSES }) + @IsOptional() + @IsIn(ONCHAIN_FILTER_STATUSES) + proofStatus?: OnchainFilterStatus; + + @ApiPropertyOptional({ description: '是否已经首次激活' }) + @IsOptional() + @Transform(({ value }) => + value === undefined || value === null || value === '' ? undefined : value === true || value === 'true', + ) + @IsBoolean() + activated?: boolean; + @ApiPropertyOptional({ description: '分组 ID' }) @IsOptional() @Type(() => Number) diff --git a/apps/api/src/trace-code/gen-code.processor.spec.ts b/apps/api/src/trace-code/gen-code.processor.spec.ts new file mode 100644 index 0000000..73f9916 --- /dev/null +++ b/apps/api/src/trace-code/gen-code.processor.spec.ts @@ -0,0 +1,138 @@ +import { BatchStatus, JobStatus } from '@artveris/shared'; +import { GenCodeProcessor } from './gen-code.processor'; + +describe('GenCodeProcessor recovery', () => { + it('continues from the actual batch count after a worker crashes following createMany', async () => { + let actualCount = 500; + const prisma = { + traceCode: { + count: jest.fn().mockImplementation(async () => actualCount), + createMany: jest.fn().mockImplementation(async ({ data }: any) => { + actualCount += data.length; + return { count: data.length }; + }), + }, + $queryRaw: jest.fn().mockResolvedValue([]), + batch: { update: jest.fn().mockResolvedValue({}) }, + $transaction: jest.fn(async (operation: (tx: any) => unknown) => operation(prisma)), + }; + const jobs = { + start: jest.fn().mockResolvedValue({}), + progress: jest.fn().mockResolvedValue({ count: 1 }), + finish: jest.fn().mockResolvedValue({ count: 1 }), + }; + const generator = { + generate: jest.fn().mockImplementation(async (count: number) => + Array.from({ length: count }, (_, index) => ({ + serialNo: actualCount + index + 1, + shortCode: `${String(index).padStart(6, '0')}${String(actualCount + index + 1).padStart(6, '0')}`, + })), + ), + }; + const processor = new GenCodeProcessor(prisma as any, jobs as any, generator as any); + jest.spyOn((processor as any).logger, 'log').mockImplementation(() => undefined); + + await processor.process({ + data: { batchId: 1, artworkId: 2, jobId: 'job-1', quantity: 600, groupId: null }, + } as any); + + expect(generator.generate).toHaveBeenCalledTimes(1); + expect(generator.generate).toHaveBeenCalledWith(100); + expect(prisma.traceCode.createMany).toHaveBeenCalledTimes(1); + expect(actualCount).toBe(600); + expect(jobs.progress).toHaveBeenNthCalledWith(1, 'job-1', 500, 0); + expect(jobs.finish).toHaveBeenCalledWith('job-1', { status: JobStatus.SUCCESS, successCount: 600 }); + expect(prisma.batch.update).toHaveBeenLastCalledWith({ + where: { id: 1 }, + data: { status: BatchStatus.DONE }, + }); + }); + + it('does not generate more codes when the recovered batch is already complete', async () => { + const prisma = { + traceCode: { count: jest.fn().mockResolvedValue(600), createMany: jest.fn() }, + batch: { update: jest.fn().mockResolvedValue({}) }, + }; + const jobs = { + start: jest.fn().mockResolvedValue({}), + progress: jest.fn().mockResolvedValue({ count: 1 }), + finish: jest.fn().mockResolvedValue({ count: 1 }), + }; + const generator = { generate: jest.fn() }; + const processor = new GenCodeProcessor(prisma as any, jobs as any, generator as any); + jest.spyOn((processor as any).logger, 'log').mockImplementation(() => undefined); + + await processor.process({ data: { batchId: 1, artworkId: 2, jobId: 'job-1', quantity: 600 } } as any); + + expect(generator.generate).not.toHaveBeenCalled(); + expect(prisma.traceCode.createMany).not.toHaveBeenCalled(); + expect(jobs.finish).toHaveBeenCalledWith('job-1', { status: JobStatus.SUCCESS, successCount: 600 }); + }); + + it('serializes duplicate workers and never exceeds the batch target', async () => { + let actualCount = 0; + let serialNo = 0; + let initialReads = 0; + let releaseInitialReads!: () => void; + const bothWorkersStarted = new Promise((resolve) => { releaseInitialReads = resolve; }); + let transactionTail = Promise.resolve(); + + const prisma: any = { + traceCode: { + count: jest.fn(async () => { + initialReads += 1; + if (initialReads <= 2) { + if (initialReads === 2) releaseInitialReads(); + await bothWorkersStarted; + return 0; + } + return actualCount; + }), + createMany: jest.fn(async ({ data }: any) => { + actualCount += data.length; + return { count: data.length }; + }), + }, + $queryRaw: jest.fn().mockResolvedValue([]), + batch: { update: jest.fn().mockResolvedValue({}) }, + $transaction: jest.fn(async (operation: (tx: any) => unknown) => { + const previous = transactionTail; + let release!: () => void; + transactionTail = new Promise((resolve) => { release = resolve; }); + await previous; + try { + return await operation(prisma); + } finally { + release(); + } + }), + }; + const jobs = { + start: jest.fn().mockResolvedValue({}), + progress: jest.fn().mockResolvedValue({ count: 1 }), + finish: jest.fn().mockResolvedValue({ count: 1 }), + }; + const generator = { + generate: jest.fn(async (count: number) => Array.from({ length: count }, () => { + serialNo += 1; + return { + serialNo, + shortCode: `${String(serialNo % 1_000_000).padStart(6, '0')}${String(serialNo).padStart(6, '0')}`, + }; + })), + }; + const processor = new GenCodeProcessor(prisma, jobs as any, generator as any); + jest.spyOn((processor as any).logger, 'log').mockImplementation(() => undefined); + const data = { batchId: 1, artworkId: 2, jobId: 'job-1', quantity: 600 }; + + await Promise.all([ + processor.process({ data } as any), + processor.process({ data } as any), + ]); + + expect(actualCount).toBe(600); + expect(prisma.traceCode.createMany.mock.calls.reduce((sum: number, [call]: any[]) => sum + call.data.length, 0)).toBe(600); + expect(jobs.finish).toHaveBeenCalledTimes(2); + expect(jobs.finish).toHaveBeenLastCalledWith('job-1', { status: JobStatus.SUCCESS, successCount: 600 }); + }); +}); diff --git a/apps/api/src/trace-code/gen-code.processor.ts b/apps/api/src/trace-code/gen-code.processor.ts index 3bf7d32..a581417 100644 --- a/apps/api/src/trace-code/gen-code.processor.ts +++ b/apps/api/src/trace-code/gen-code.processor.ts @@ -1,10 +1,10 @@ import { Processor, WorkerHost } from '@nestjs/bullmq'; import { Logger } from '@nestjs/common'; +import { Prisma } from '@prisma/client'; import { Job } from 'bullmq'; import { BatchStatus, JobStatus, QUEUE_NAMES } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; import { JobsService } from '../jobs/jobs.service'; -import { TraceCodeService } from './trace-code.service'; import { TraceCodeGeneratorService } from './trace-code-generator.service'; interface GenJobData { @@ -22,7 +22,6 @@ export class GenCodeProcessor extends WorkerHost { constructor( private readonly prisma: PrismaService, private readonly jobs: JobsService, - private readonly traceCode: TraceCodeService, private readonly generator: TraceCodeGeneratorService, ) { super(); @@ -36,25 +35,47 @@ export class GenCodeProcessor extends WorkerHost { let generated = 0; const chunkSize = 500; try { + generated = await this.prisma.traceCode.count({ where: { batchId } }); + if (generated > quantity) throw new Error('批次实际生码数量超过目标数量,请检查批次数据'); + await this.jobs.progress(jobId, generated, 0); + await this.prisma.batch.update({ where: { id: batchId }, data: { generatedCount: generated } }); while (generated < quantity) { const n = Math.min(chunkSize, quantity - generated); - const shortCodes = await this.generator.generate(n); - const rows = shortCodes.map((shortCode) => { + const generatedCodes = await this.generator.generate(n); + const rows = generatedCodes.map(({ shortCode, serialNo }) => { return { shortCode, + serialNo, artworkId, batchId, groupId: groupId ?? null, url: null, }; }); - const result = await this.prisma.traceCode.createMany({ data: rows, skipDuplicates: true }); - generated += result.count; - await this.jobs.progress(jobId, generated, 0); - await this.prisma.batch.update({ - where: { id: batchId }, - data: { generatedCount: generated }, + const persisted = await this.prisma.$transaction(async (tx) => { + await tx.$queryRaw(Prisma.sql`SELECT id FROM \`batch\` WHERE id = ${batchId} FOR UPDATE`); + const current = await tx.traceCode.count({ where: { batchId } }); + if (current > quantity) throw new Error('批次实际生码数量超过目标数量,请检查批次数据'); + + const remaining = quantity - current; + if (remaining === 0) { + await tx.batch.update({ where: { id: batchId }, data: { generatedCount: current } }); + return { generated: current, inserted: 0 }; + } + + const result = await tx.traceCode.createMany({ + data: rows.slice(0, remaining), + skipDuplicates: true, + }); + const nextCount = current + result.count; + await tx.batch.update({ where: { id: batchId }, data: { generatedCount: nextCount } }); + return { generated: nextCount, inserted: result.count }; }); + generated = persisted.generated; + if (persisted.inserted === 0 && generated < quantity) { + throw new Error('生码写入未产生新记录,请稍后重试'); + } + await this.jobs.progress(jobId, generated, 0); } await this.jobs.finish(jobId, { status: JobStatus.SUCCESS, successCount: generated }); await this.prisma.batch.update({ where: { id: batchId }, data: { status: BatchStatus.DONE } }); diff --git a/apps/api/src/trace-code/trace-code-generator.service.spec.ts b/apps/api/src/trace-code/trace-code-generator.service.spec.ts index c4b1954..705b374 100644 --- a/apps/api/src/trace-code/trace-code-generator.service.spec.ts +++ b/apps/api/src/trace-code/trace-code-generator.service.spec.ts @@ -1,12 +1,9 @@ import { TraceCodeGeneratorService } from './trace-code-generator.service'; describe('TraceCodeGeneratorService', () => { + let nextSeq: number; const prisma: any = { - systemSetting: { - findUnique: jest.fn(), - create: jest.fn(), - }, - traceCodeDailySequence: { + traceCodeSequence: { upsert: jest.fn(), update: jest.fn(), }, @@ -14,27 +11,43 @@ describe('TraceCodeGeneratorService', () => { }; beforeEach(() => { - jest.useFakeTimers().setSystemTime(new Date('2026-07-06T08:00:00.000Z')); - prisma.systemSetting.findUnique.mockResolvedValue({ value: 'salt-for-test' }); - prisma.traceCodeDailySequence.upsert.mockResolvedValue({}); - prisma.traceCodeDailySequence.update.mockResolvedValue({ nextSeq: 1000 }); + nextSeq = 1; + prisma.traceCodeSequence.upsert.mockResolvedValue({ id: 1, nextSeq }); + prisma.traceCodeSequence.update.mockImplementation(async ({ data }: any) => { + nextSeq += data.nextSeq.increment; + return { id: 1, nextSeq }; + }); }); - afterEach(() => { - jest.useRealTimers(); - jest.clearAllMocks(); - }); + afterEach(() => jest.clearAllMocks()); - it('generates unique 12-digit codes with the Shanghai date embedded', async () => { + it('uses a random six-digit prefix and a global six-digit sequence suffix', async () => { const service = new TraceCodeGeneratorService(prisma); - const codes = await service.generate(1000); + const codes = await service.generate(3); - expect(codes).toHaveLength(1000); - expect(new Set(codes).size).toBe(1000); - for (const code of codes) { - expect(code).toMatch(/^\d{12}$/); - expect(`${code.slice(2, 4)}${code.slice(5, 7)}${code.slice(8, 10)}`).toBe('260706'); - } - expect(codes.slice(0, 5)).not.toEqual(['002600700600', '002600700601', '002600700602', '002600700603', '002600700604']); + expect(codes.map((item) => item.serialNo)).toEqual([1, 2, 3]); + expect(codes.map((item) => item.shortCode.slice(6))).toEqual(['000001', '000002', '000003']); + expect(codes.every((item) => /^\d{12}$/.test(item.shortCode))).toBe(true); + }); + + it('preserves leading zeroes in the random prefix', () => { + const service = new TraceCodeGeneratorService(prisma); + expect((service as any).formatCode(1, 42)).toBe('000042000001'); + }); + + it('allows the final sequence and rejects allocation past 999999', async () => { + nextSeq = 999_999; + const service = new TraceCodeGeneratorService(prisma); + + await expect(service.generate(1)).resolves.toEqual([ + expect.objectContaining({ serialNo: 999_999, shortCode: expect.stringMatching(/^\d{6}999999$/) }), + ]); + await expect(service.generate(1)).rejects.toThrow('trace.code.sequenceExhausted'); + }); + + it('rejects invalid allocation quantities before opening a transaction', async () => { + const service = new TraceCodeGeneratorService(prisma); + await expect(service.generate(0)).rejects.toThrow('trace.code.invalidQuantity'); + expect(prisma.$transaction).not.toHaveBeenCalled(); }); }); diff --git a/apps/api/src/trace-code/trace-code-generator.service.ts b/apps/api/src/trace-code/trace-code-generator.service.ts index 7b3d0ee..f45896a 100644 --- a/apps/api/src/trace-code/trace-code-generator.service.ts +++ b/apps/api/src/trace-code/trace-code-generator.service.ts @@ -1,15 +1,18 @@ import { Injectable } from '@nestjs/common'; -import { createHmac, randomBytes } from 'crypto'; +import { randomInt } from 'crypto'; import { Prisma } from '@prisma/client'; import { SHORT_CODE_LENGTH } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; -const TRACE_CODE_SALT_KEY = 'traceCodeSalt'; -const MAX_DAILY_SEQUENCE = 1_000_000; -const FEISTEL_ROUNDS = 4; +const SEQUENCE_ID = 1; +const MAX_SEQUENCE = 999_999; + +export interface GeneratedTraceCode { + shortCode: string; + serialNo: number; +} interface SequenceRange { - dateKey: string; start: number; end: number; } @@ -18,109 +21,46 @@ interface SequenceRange { export class TraceCodeGeneratorService { constructor(private readonly prisma: PrismaService) {} - async ensureSalt(): Promise { - // 溯源码盐优先以 .env 的 TRACE_CODE_SALT 为权威来源(安装向导写入、升级不覆盖); - // DB 中的 systemSetting.traceCodeSalt 仅作兜底缓存,二者以 env 为准,使「勿更改」注释名副其实。 - const envSalt = process.env.TRACE_CODE_SALT?.trim(); - if (envSalt) { - const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } }); - if (!existing?.value) { - await this.prisma.systemSetting.upsert({ - where: { key: TRACE_CODE_SALT_KEY }, - update: { value: envSalt }, - create: { key: TRACE_CODE_SALT_KEY, value: envSalt }, - }); - } - return envSalt; + async generate(count: number): Promise { + if (!Number.isInteger(count) || count < 1 || count > MAX_SEQUENCE) { + throw new Error('trace.code.invalidQuantity'); } - const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } }); - if (existing?.value) return existing.value; - const salt = randomBytes(32).toString('hex'); - try { - await this.prisma.systemSetting.create({ data: { key: TRACE_CODE_SALT_KEY, value: salt } }); - return salt; - } catch (e) { - if (this.isUniqueError(e)) { - const row = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } }); - if (row?.value) return row.value; - } - throw e; - } - } - - async generate(count: number): Promise { - const salt = await this.ensureSalt(); const range = await this.allocateRange(count); - return Array.from({ length: range.end - range.start + 1 }, (_, index) => - this.formatCode(this.permute6(range.start + index, salt, range.dateKey), range.dateKey), - ); + return Array.from({ length: count }, (_, index) => { + const serialNo = range.start + index; + return { serialNo, shortCode: this.formatCode(serialNo) }; + }); } private async allocateRange(count: number): Promise { - const dateKey = this.shanghaiDateKey(); for (let attempt = 0; attempt < 3; attempt += 1) { try { return await this.prisma.$transaction(async (tx) => { - await tx.traceCodeDailySequence.upsert({ - where: { dateKey }, + await tx.traceCodeSequence.upsert({ + where: { id: SEQUENCE_ID }, update: {}, - create: { dateKey, nextSeq: 0 }, + create: { id: SEQUENCE_ID, nextSeq: 1 }, }); - const row = await tx.traceCodeDailySequence.update({ - where: { dateKey }, + const row = await tx.traceCodeSequence.update({ + where: { id: SEQUENCE_ID }, data: { nextSeq: { increment: count } }, }); const start = row.nextSeq - count; const end = row.nextSeq - 1; - if (end >= MAX_DAILY_SEQUENCE) { - throw new Error('trace.code.dailyLimitExceeded'); + if (start < 1 || end > MAX_SEQUENCE) { + throw new Error('trace.code.sequenceExhausted'); } - return { dateKey, start, end }; + return { start, end }; }); - } catch (e) { - if (!this.isUniqueError(e) || attempt === 2) throw e; + } catch (error) { + if (!this.isUniqueError(error) || attempt === 2) throw error; } } throw new Error('trace.code.sequenceAllocationFailed'); } - private shanghaiDateKey(date = new Date()): string { - const parts = new Intl.DateTimeFormat('en-US', { - timeZone: 'Asia/Shanghai', - year: '2-digit', - month: '2-digit', - day: '2-digit', - }).formatToParts(date); - const get = (type: string) => parts.find((part) => part.type === type)?.value.padStart(2, '0') ?? '00'; - return `${get('year')}${get('month')}${get('day')}`; - } - - private permute6(seq: number, salt: string, dateKey: string): string { - let left = Math.floor(seq / 1000); - let right = seq % 1000; - const keys = this.roundKeys(salt, dateKey); - for (let round = 0; round < FEISTEL_ROUNDS; round += 1) { - const nextLeft = right; - const f = (right * keys[round].mul + keys[round].add) % 1000; - right = (left + f) % 1000; - left = nextLeft; - } - return `${left.toString().padStart(3, '0')}${right.toString().padStart(3, '0')}`; - } - - private roundKeys(salt: string, dateKey: string): Array<{ mul: number; add: number }> { - const digest = createHmac('sha256', salt).update(`trace-code:${dateKey}`).digest(); - return Array.from({ length: FEISTEL_ROUNDS }, (_, index) => { - const rawMul = digest.readUInt16BE(index * 4) % 1000; - return { - mul: rawMul % 2 === 0 ? rawMul + 1 : rawMul, - add: digest.readUInt16BE(index * 4 + 2) % 1000, - }; - }); - } - - private formatCode(scrambled: string, dateKey: string): string { - const code = `${scrambled.slice(0, 2)}${dateKey.slice(0, 2)}${scrambled[2]}${dateKey.slice(2, 4)}${scrambled[3]}${dateKey.slice(4, 6)}${scrambled.slice(4)}`; + private formatCode(serialNo: number, randomValue = randomInt(0, 1_000_000)): string { + const code = `${randomValue.toString().padStart(6, '0')}${serialNo.toString().padStart(6, '0')}`; if (code.length !== SHORT_CODE_LENGTH || !/^\d{12}$/.test(code)) { throw new Error('trace.code.invalidGeneratedCode'); } diff --git a/apps/api/src/trace-code/trace-code.controller.ts b/apps/api/src/trace-code/trace-code.controller.ts index b201a7f..ddd9987 100644 --- a/apps/api/src/trace-code/trace-code.controller.ts +++ b/apps/api/src/trace-code/trace-code.controller.ts @@ -32,6 +32,7 @@ import { import { Roles } from '../common/decorators/roles.decorator'; import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator'; import { parseBigId } from '../common/utils/bigint.util'; +import { MatchTraceCodesDto } from '../common/dto/trace-code-selection.dto'; @ApiTags('批量生码') @ApiBearerAuth() @@ -124,6 +125,13 @@ export class TraceCodeController { return this.service.batchDelete(dto); } + @Post('trace-codes/match') + @Roles(RoleType.OPERATOR) + @ApiOperation({ summary: '按追溯码批量匹配并校验操作资格' }) + matchCodes(@Body() dto: MatchTraceCodesDto) { + return this.service.matchCodes(dto); + } + @Put('trace-codes/:id') @Roles(RoleType.OPERATOR) @ApiOperation({ summary: '更新单个追溯码' }) diff --git a/apps/api/src/trace-code/trace-code.service.spec.ts b/apps/api/src/trace-code/trace-code.service.spec.ts new file mode 100644 index 0000000..3d7538d --- /dev/null +++ b/apps/api/src/trace-code/trace-code.service.spec.ts @@ -0,0 +1,65 @@ +import { TraceCodeService } from './trace-code.service'; + +function createHarness(codes: any[]) { + const prisma = { + traceCode: { + findMany: jest.fn().mockResolvedValue(codes), + deleteMany: jest.fn().mockResolvedValue({ count: codes.length }), + }, + queryLog: { updateMany: jest.fn().mockResolvedValue({ count: 0 }) }, + batch: { update: jest.fn().mockResolvedValue({}) }, + $transaction: jest.fn().mockImplementation(async (operations: any[]) => Promise.all(operations)), + }; + const service = new TraceCodeService( + prisma as any, + {} as any, + {} as any, + {} as any, + {} as any, + ); + return { service, prisma }; +} + +function code(overrides: Record = {}) { + return { + id: 1n, + shortCode: '482731000001', + batchId: 10, + outbound: null, + proofs: [], + jobItems: [], + ...overrides, + }; +} + +describe('TraceCodeService.batchDelete', () => { + it.each([ + [code({ outbound: { id: 2n } }), '已登记出库'], + [code({ proofs: [{ status: 'ONCHAIN' }] }), '已上链'], + [code({ proofs: [{ status: 'UNKNOWN' }] }), '存在上链记录'], + [code({ jobItems: [{ id: 3n }] }), '存在批量操作记录'], + ])('explicitly rejects a referenced trace code', async (blocked, message) => { + const harness = createHarness([blocked]); + + await expect(harness.service.batchDelete({ ids: ['1'] })).rejects.toThrow(message); + expect(harness.prisma.traceCode.deleteMany).not.toHaveBeenCalled(); + }); + + it('deduplicates ids and updates batch counters in the same transaction', async () => { + const harness = createHarness([code()]); + + await expect(harness.service.batchDelete({ ids: ['1', '1'] })).resolves.toEqual({ success: true, count: 1 }); + expect(harness.prisma.traceCode.findMany).toHaveBeenCalledWith({ + where: { id: { in: [1n] } }, + select: expect.objectContaining({ outbound: expect.anything(), proofs: expect.anything(), jobItems: expect.anything() }), + }); + expect(harness.prisma.queryLog.updateMany).toHaveBeenCalledWith({ + where: { traceCodeId: { in: [1n] } }, + data: { traceCodeId: null }, + }); + expect(harness.prisma.batch.update).toHaveBeenCalledWith({ + where: { id: 10 }, + data: { quantity: { decrement: 1 }, generatedCount: { decrement: 1 } }, + }); + }); +}); diff --git a/apps/api/src/trace-code/trace-code.service.ts b/apps/api/src/trace-code/trace-code.service.ts index a2c6f76..4a644be 100644 --- a/apps/api/src/trace-code/trace-code.service.ts +++ b/apps/api/src/trace-code/trace-code.service.ts @@ -16,6 +16,8 @@ import { buildOrderBy } from '../common/utils/sort.util'; import { parseBigId } from '../common/utils/bigint.util'; import { JobsService } from '../jobs/jobs.service'; import { SettingsService } from '../settings/settings.service'; +import { buildTraceCodeFilterWhere } from '../common/utils/trace-code-selection.util'; +import { MatchTraceCodesDto } from '../common/dto/trace-code-selection.dto'; import { BatchDeleteDto, BatchGroupDto, @@ -46,20 +48,28 @@ export class TraceCodeService { return `${clientBase}/#/trace/${encodeURIComponent(shortCode)}`; } - private mapOutImages(code: { outImages?: unknown }) { - const keys = Array.isArray(code.outImages) - ? (code.outImages as Array<{ key?: string; name?: string; type?: string }>) - .map((item) => (typeof item === 'string' ? { key: item } : item)) - .filter((item) => item?.key) - : []; - return keys.map((item) => ({ - ...item, - url: this.storage.getUrl(item.key as string), - type: item.type || 'image', - name: item.name || (item.key as string).split('/').pop() || '出库实况图', + private mapOutImages(outbound: { images?: Array<{ id: bigint; fileKey: string; fileName: string; mimeType: string; size: bigint; width: number; height: number; sortOrder: number }> } | null) { + return (outbound?.images ?? []).map((item) => ({ + id: item.id, + key: item.fileKey, + url: this.storage.getUrl(item.fileKey), + type: 'image', + name: item.fileName, + mimeType: item.mimeType, + size: item.size, + width: item.width, + height: item.height, + sortOrder: item.sortOrder, })); } + private hasPrimaryImage(images: unknown): boolean { + if (!Array.isArray(images) || !images.length) return false; + const first = images[0] as string | { key?: unknown } | null; + const key = typeof first === 'string' ? first : first?.key; + return typeof key === 'string' && key.trim().length > 0 && !/^data:/i.test(key.trim()); + } + async generateBatch(dto: GenerateBatchDto, userId: number) { const artwork = await this.prisma.artwork.findFirst({ where: { id: dto.artworkId, deletedAt: null }, @@ -346,31 +356,60 @@ export class TraceCodeService { } async batchDelete(dto: BatchDeleteDto) { - const ids = dto.ids.map((item) => parseBigId(item, '追溯码 ID')); + const ids = [...new Set(dto.ids)].map((item) => parseBigId(item, '追溯码 ID')); const codes = await this.prisma.traceCode.findMany({ where: { id: { in: ids } }, - select: { id: true, batchId: true }, + select: { + id: true, + batchId: true, + shortCode: true, + outbound: { select: { id: true } }, + proofs: { select: { status: true }, take: 1 }, + jobItems: { select: { id: true }, take: 1 }, + }, }); if (codes.length !== ids.length) { throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '部分追溯码不存在', 404); } + const blocked = codes.find((code) => code.outbound || code.proofs.length || code.jobItems.length); + if (blocked) { + const reason = blocked.outbound + ? '已登记出库' + : blocked.proofs[0]?.status === 'ONCHAIN' + ? '已上链' + : blocked.proofs.length + ? '存在上链记录' + : '存在批量操作记录'; + throw new BusinessException( + ErrorCode.BAD_REQUEST, + `追溯码 ${blocked.shortCode} ${reason},不可删除`, + 409, + ); + } const batchCounts = new Map(); for (const code of codes) { batchCounts.set(code.batchId, (batchCounts.get(code.batchId) ?? 0) + 1); } - await this.prisma.$transaction([ - this.prisma.queryLog.updateMany({ - where: { traceCodeId: { in: ids } }, - data: { traceCodeId: null }, - }), - this.prisma.traceCode.deleteMany({ where: { id: { in: ids } } }), - ...[...batchCounts.entries()].map(([batchId, count]) => - this.prisma.batch.update({ - where: { id: batchId }, - data: { quantity: { decrement: count }, generatedCount: { decrement: count } }, + try { + await this.prisma.$transaction([ + this.prisma.queryLog.updateMany({ + where: { traceCodeId: { in: ids } }, + data: { traceCodeId: null }, }), - ), - ]); + this.prisma.traceCode.deleteMany({ where: { id: { in: ids } } }), + ...[...batchCounts.entries()].map(([batchId, count]) => + this.prisma.batch.update({ + where: { id: batchId }, + data: { quantity: { decrement: count }, generatedCount: { decrement: count } }, + }), + ), + ]); + } catch (error) { + if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2003') { + throw new BusinessException(ErrorCode.BAD_REQUEST, '追溯码已被出库、上链或批量任务引用,不可删除', 409); + } + throw error; + } return { success: true, count: ids.length }; } @@ -391,51 +430,48 @@ export class TraceCodeService { return buildPage(list, total, query.page, query.pageSize); } - private buildTraceCodeWhere( - query: Pick, - ): Prisma.TraceCodeWhereInput { - const where: Prisma.TraceCodeWhereInput = {}; - const and: Prisma.TraceCodeWhereInput[] = []; - if (query.artworkId) where.artworkId = query.artworkId; - if (query.batchId) where.batchId = query.batchId; - if (query.groupId) where.groupId = query.groupId; - if (query.status) where.status = query.status; - if (query.outboundStatus === 'OUTBOUND') { - and.push({ OR: [{ outTime: { not: null } }, { outImages: { not: Prisma.DbNull } }] }); - } else if (query.outboundStatus === 'NOT_OUTBOUND') { - and.push({ outTime: null, outImages: { equals: Prisma.DbNull } }); - } - if (query.keyword) { - and.push({ - OR: [ - { shortCode: { contains: query.keyword } }, - { url: { contains: query.keyword } }, - { remark: { contains: query.keyword } }, - { artwork: { archiveNo: { contains: query.keyword } } }, - { artwork: { title: { contains: query.keyword } } }, - { artwork: { artist: { contains: query.keyword } } }, - { batch: { batchNo: { contains: query.keyword } } }, - { group: { name: { contains: query.keyword } } }, - ], - }); - } - if (and.length) where.AND = and; - return where; + private buildTraceCodeWhere(query: QueryTraceCodeDto | ExportTraceCodeDto): Prisma.TraceCodeWhereInput { + return buildTraceCodeFilterWhere(query); } async list(query: QueryTraceCodeDto) { const where = this.buildTraceCodeWhere(query); - const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt', 'outTime', 'firstActivatedAt'] as const, { id: 'desc' }); - const [list, total] = await this.prisma.$transaction([ + const operation = query.proofStatus ? 'ONCHAIN' : query.outboundStatus ? 'OUTBOUND' : null; + const eligibilityWhere: Prisma.TraceCodeWhereInput = operation === 'ONCHAIN' + ? { + status: { in: ['INACTIVE', 'ACTIVE'] }, + artwork: { + is: { + deletedAt: null, + status: 'ACTIVE', + auditStatus: 'APPROVED', + images: { not: Prisma.DbNull }, + }, + }, + OR: [{ proofs: { none: {} } }, { proofs: { some: { status: 'FAILED' } } }], + } + : operation === 'OUTBOUND' + ? { outbound: { is: null } } + : {}; + const orderBy: Prisma.TraceCodeOrderByWithRelationInput = query.sortField === 'outTime' + ? { outbound: { outTime: query.sortOrder === 'asc' || query.sortOrder === 'ascend' ? 'asc' : 'desc' } } + : buildOrderBy(query.sortField, query.sortOrder, ['createdAt', 'firstActivatedAt'] as const, { id: 'desc' }); + const [list, total, eligibleTotal] = await this.prisma.$transaction([ this.prisma.traceCode.findMany({ where, include: { - artwork: { select: { id: true, title: true, archiveNo: true } }, + artwork: { select: { id: true, title: true, archiveNo: true, status: true, auditStatus: true, images: true } }, batch: { select: { id: true, batchNo: true } }, group: { select: { id: true, name: true } }, + outbound: { + include: { + images: { orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }], take: 1 }, + _count: { select: { images: true } }, + }, + }, proofs: { orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], - take: 10, + take: 1, }, }, orderBy, @@ -443,27 +479,120 @@ export class TraceCodeService { take: query.take, }), this.prisma.traceCode.count({ where }), + this.prisma.traceCode.count({ where: operation ? { AND: [where, eligibilityWhere] } : where }), ]); // 链接统一动态生成(DB 不固化 url,换客户端地址后列表/导出/二维码自动跟随);base 每页只取一次 const clientBase = await this.settings.getClientBaseUrl(); - return buildPage( + const page = buildPage( list.map((code) => { - const { proofs, ...rest } = code; + const { proofs, outbound, ...rest } = code; const latestOnchainProof = proofs.find((p) => p.status === 'ONCHAIN') ?? null; - const outImages = this.mapOutImages(code); + const latestAnyProof = proofs[0] ?? null; + const outImages = this.mapOutImages(outbound); + const hasPrimaryImage = this.hasPrimaryImage(code.artwork.images); + const onchainEligible = + ['INACTIVE', 'ACTIVE'].includes(code.status) && + code.artwork.status === 'ACTIVE' && + code.artwork.auditStatus === 'APPROVED' && + hasPrimaryImage && + (!latestAnyProof || latestAnyProof.status === 'FAILED'); + const outboundEligible = !outbound; + const eligible = operation === 'ONCHAIN' ? onchainEligible : operation === 'OUTBOUND' ? outboundEligible : true; + let onchainReason: string | null = null; + if (!['INACTIVE', 'ACTIVE'].includes(code.status)) onchainReason = '停用或异常追溯码不可上链'; + else if (code.artwork.status !== 'ACTIVE' || code.artwork.auditStatus !== 'APPROVED') onchainReason = '作品未生效或未审核通过'; + else if (!hasPrimaryImage) onchainReason = '作品缺少有效主图'; + else if (latestAnyProof?.status === 'ONCHAIN') onchainReason = '该追溯码已上链'; + else if (latestAnyProof && latestAnyProof.status !== 'FAILED') onchainReason = '该追溯码正在上链处理中'; + const outboundReason = outboundEligible ? null : '该追溯码已登记出库'; + const reason = operation === 'ONCHAIN' ? onchainReason : operation === 'OUTBOUND' ? outboundReason : null; + const { images: _artworkImages, ...artwork } = code.artwork; return { ...rest, + artwork, + outbound: outbound + ? { id: outbound.id, outTime: outbound.outTime, remark: outbound.remark, createdAt: outbound.createdAt, updatedAt: outbound.updatedAt } + : null, + outTime: outbound?.outTime ?? null, + remark: outbound?.remark ?? null, url: `${clientBase}/#/trace/${encodeURIComponent(code.shortCode)}`, outImageUrl: outImages[0]?.url ?? null, outImages, + outImageCount: outbound?._count.images ?? 0, latestProof: latestOnchainProof, - latestAnyProof: proofs[0] ?? null, + latestAnyProof, + proofStatus: latestAnyProof?.status ?? 'NONE', + onchainEligible, + onchainReason, + outboundEligible, + outboundReason, + eligible, + reason, }; }), total, query.page, query.pageSize, ); + return { ...page, eligibleTotal }; + } + + async matchCodes(dto: MatchTraceCodesDto) { + const normalized = dto.codes.map((code) => code.trim()).filter(Boolean); + const seen = new Set(); + const duplicates = [...new Set(normalized.filter((code) => (seen.has(code) ? true : (seen.add(code), false))))]; + const uniqueCodes = [...seen]; + const codes = await this.prisma.traceCode.findMany({ + where: { shortCode: { in: uniqueCodes } }, + include: { + artwork: { select: { id: true, title: true, archiveNo: true, status: true, auditStatus: true, images: true } }, + batch: { select: { id: true, batchNo: true } }, + group: { select: { id: true, name: true } }, + outbound: { select: { id: true, outTime: true } }, + proofs: { orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], take: 1 }, + }, + }); + const byCode = new Map(codes.map((code) => [code.shortCode, code])); + const missing = uniqueCodes.filter((code) => !byCode.has(code)); + const matched = uniqueCodes.flatMap((shortCode) => { + const code = byCode.get(shortCode); + if (!code) return []; + const proof = code.proofs[0] ?? null; + const hasPrimaryImage = this.hasPrimaryImage(code.artwork.images); + let eligible = false; + let reason: string | null = null; + if (dto.operation === 'OUTBOUND') { + eligible = !code.outbound; + if (!eligible) reason = '该追溯码已登记出库'; + } else { + eligible = + ['INACTIVE', 'ACTIVE'].includes(code.status) && + code.artwork.status === 'ACTIVE' && + code.artwork.auditStatus === 'APPROVED' && + hasPrimaryImage && + (!proof || proof.status === 'FAILED'); + if (!['INACTIVE', 'ACTIVE'].includes(code.status)) reason = '停用或异常追溯码不可上链'; + else if (code.artwork.status !== 'ACTIVE' || code.artwork.auditStatus !== 'APPROVED') reason = '作品未生效或未审核通过'; + else if (!hasPrimaryImage) reason = '作品缺少有效主图'; + else if (proof?.status === 'ONCHAIN') reason = '该追溯码已上链'; + else if (proof && proof.status !== 'FAILED') reason = '该追溯码正在上链处理中'; + } + const { images: _artworkImages, ...artwork } = code.artwork; + return [{ + id: code.id, + shortCode: code.shortCode, + status: code.status, + artwork, + batch: code.batch, + group: code.group, + outbound: code.outbound, + proof, + proofStatus: proof?.status ?? 'NONE', + eligible, + reason, + }]; + }); + return { matched, missing, duplicates }; } async getQrPng(id: bigint): Promise { diff --git a/apps/api/src/trace-node/dto/trace-node.dto.ts b/apps/api/src/trace-node/dto/trace-node.dto.ts deleted file mode 100644 index e776924..0000000 --- a/apps/api/src/trace-node/dto/trace-node.dto.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; -import { Type } from 'class-transformer'; -import { - IsArray, - IsDateString, - IsEnum, - IsInt, - IsNotEmpty, - IsOptional, - IsString, - MaxLength, - ValidateNested, -} from 'class-validator'; -import { NodeType } from '@artveris/shared'; -import { MediaItemDto } from '../../artwork/dto/artwork.dto'; - -export class CreateNodeDto { - @ApiProperty({ description: '节点类型', enum: NodeType }) - @IsEnum(NodeType) - nodeType!: NodeType; - - @ApiProperty({ description: '节点标题' }) - @IsString() - @IsNotEmpty() - @MaxLength(80) - title!: string; - - @ApiPropertyOptional({ description: '发生时间' }) - @IsOptional() - @IsDateString() - occurredAt?: string; - - @ApiPropertyOptional({ description: '地点' }) - @IsOptional() - @IsString() - @MaxLength(120) - location?: string; - - @ApiPropertyOptional({ description: '说明' }) - @IsOptional() - @IsString() - @MaxLength(2000) - description?: string; - - @ApiPropertyOptional({ description: '图片/视频', type: [MediaItemDto] }) - @IsOptional() - @IsArray() - @ValidateNested({ each: true }) - @Type(() => MediaItemDto) - mediaFiles?: MediaItemDto[]; - - @ApiPropertyOptional({ description: '排序' }) - @IsOptional() - @IsInt() - sortOrder?: number; -} - -export class UpdateNodeDto extends CreateNodeDto {} - -export class ReorderNodeDto { - @ApiProperty({ description: '按目标顺序排列的节点 ID 列表', type: [Number] }) - @IsArray() - @IsInt({ each: true }) - ids!: number[]; -} diff --git a/apps/api/src/trace-node/trace-node.controller.ts b/apps/api/src/trace-node/trace-node.controller.ts index d64b965..bd96376 100644 --- a/apps/api/src/trace-node/trace-node.controller.ts +++ b/apps/api/src/trace-node/trace-node.controller.ts @@ -1,9 +1,6 @@ -import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put } from '@nestjs/common'; +import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common'; import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; -import { RoleType } from '@artveris/shared'; import { TraceNodeService } from './trace-node.service'; -import { CreateNodeDto, ReorderNodeDto, UpdateNodeDto } from './dto/trace-node.dto'; -import { Roles } from '../common/decorators/roles.decorator'; @ApiTags('溯源节点') @ApiBearerAuth() @@ -16,32 +13,4 @@ export class TraceNodeController { list(@Param('artworkId', ParseIntPipe) artworkId: number) { return this.nodeService.listByArtwork(artworkId); } - - @Post('artworks/:artworkId/nodes') - @Roles(RoleType.OPERATOR) - @ApiOperation({ summary: '新增溯源节点' }) - create(@Param('artworkId', ParseIntPipe) artworkId: number, @Body() dto: CreateNodeDto) { - return this.nodeService.create(artworkId, dto); - } - - @Put('artworks/:artworkId/nodes/reorder') - @Roles(RoleType.OPERATOR) - @ApiOperation({ summary: '调整节点顺序' }) - reorder(@Param('artworkId', ParseIntPipe) artworkId: number, @Body() dto: ReorderNodeDto) { - return this.nodeService.reorder(artworkId, dto); - } - - @Put('nodes/:id') - @Roles(RoleType.OPERATOR) - @ApiOperation({ summary: '更新溯源节点' }) - update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateNodeDto) { - return this.nodeService.update(id, dto); - } - - @Delete('nodes/:id') - @Roles(RoleType.OPERATOR) - @ApiOperation({ summary: '删除溯源节点' }) - remove(@Param('id', ParseIntPipe) id: number) { - return this.nodeService.remove(id); - } } diff --git a/apps/api/src/trace-node/trace-node.module.ts b/apps/api/src/trace-node/trace-node.module.ts index 002d921..0fe008d 100644 --- a/apps/api/src/trace-node/trace-node.module.ts +++ b/apps/api/src/trace-node/trace-node.module.ts @@ -5,6 +5,5 @@ import { TraceNodeController } from './trace-node.controller'; @Module({ controllers: [TraceNodeController], providers: [TraceNodeService], - exports: [TraceNodeService], }) export class TraceNodeModule {} diff --git a/apps/api/src/trace-node/trace-node.service.ts b/apps/api/src/trace-node/trace-node.service.ts index cf83c82..d99189f 100644 --- a/apps/api/src/trace-node/trace-node.service.ts +++ b/apps/api/src/trace-node/trace-node.service.ts @@ -1,10 +1,6 @@ import { Injectable } from '@nestjs/common'; -import { Prisma } from '@prisma/client'; -import { ErrorCode } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; import { StorageService } from '../storage/storage.service'; -import { BusinessException } from '../common/exceptions/business.exception'; -import { CreateNodeDto, ReorderNodeDto, UpdateNodeDto } from './dto/trace-node.dto'; @Injectable() export class TraceNodeService { @@ -20,11 +16,6 @@ export class TraceNodeService { .map((i) => ({ ...i, url: this.storage.getUrl(i.key) })); } - private async ensureArtwork(artworkId: number) { - const a = await this.prisma.artwork.findFirst({ where: { id: artworkId, deletedAt: null } }); - if (!a) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404); - } - async listByArtwork(artworkId: number) { const nodes = await this.prisma.traceNode.findMany({ where: { artworkId }, @@ -32,64 +23,4 @@ export class TraceNodeService { }); return nodes.map((n) => ({ ...n, mediaFiles: this.mapMedia(n.mediaFiles) })); } - - async create(artworkId: number, dto: CreateNodeDto) { - await this.ensureArtwork(artworkId); - const count = await this.prisma.traceNode.count({ where: { artworkId } }); - const node = await this.prisma.traceNode.create({ - data: { - artworkId, - nodeType: dto.nodeType, - title: dto.title, - occurredAt: dto.occurredAt ? new Date(dto.occurredAt) : null, - location: dto.location, - description: dto.description, - mediaFiles: (dto.mediaFiles ?? []) as unknown as Prisma.InputJsonValue, - sortOrder: dto.sortOrder ?? count, - }, - }); - return { ...node, mediaFiles: this.mapMedia(node.mediaFiles) }; - } - - async update(id: number, dto: UpdateNodeDto) { - await this.ensureNode(id); - const node = await this.prisma.traceNode.update({ - where: { id }, - data: { - nodeType: dto.nodeType, - title: dto.title, - occurredAt: dto.occurredAt ? new Date(dto.occurredAt) : null, - location: dto.location, - description: dto.description, - mediaFiles: (dto.mediaFiles ?? []) as unknown as Prisma.InputJsonValue, - sortOrder: dto.sortOrder, - }, - }); - return { ...node, mediaFiles: this.mapMedia(node.mediaFiles) }; - } - - async remove(id: number) { - await this.ensureNode(id); - await this.prisma.traceNode.delete({ where: { id } }); - return { success: true }; - } - - async reorder(artworkId: number, dto: ReorderNodeDto) { - await this.ensureArtwork(artworkId); - await this.prisma.$transaction( - dto.ids.map((id, index) => - this.prisma.traceNode.updateMany({ - where: { id, artworkId }, - data: { sortOrder: index }, - }), - ), - ); - return { success: true }; - } - - private async ensureNode(id: number) { - const n = await this.prisma.traceNode.findUnique({ where: { id } }); - if (!n) throw new BusinessException(ErrorCode.NOT_FOUND, '节点不存在', 404); - return n; - } } diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts index 95047d2..c786646 100644 --- a/packages/shared/src/constants.ts +++ b/packages/shared/src/constants.ts @@ -2,6 +2,7 @@ export const QUEUE_NAMES = { GEN_CODE: 'gen-code', IMPORT_OUTBOUND: 'import-outbound', IMPORT_OUTBOUND_PREVIEW: 'import-outbound-preview', + BATCH_OUTBOUND: 'batch-outbound', WATERMARK: 'watermark', ONCHAIN: 'onchain', BACKUP: 'backup', @@ -10,6 +11,7 @@ export const QUEUE_NAMES = { export const SHORT_CODE_LENGTH = 12; export const TRACE_CODE_PATTERN = /^\d{12}$/; +export const MAX_BATCH_SELECTION = 10_000; export const MAX_IMAGE_SIZE = 10 * 1024 * 1024; export const MAX_VIDEO_SIZE = 100 * 1024 * 1024; @@ -46,12 +48,6 @@ export const OUTBOUND_IMPORT_COLUMNS: ImportColumn[] = [ required: true, note: '必填,中国标准时间,格式 YYYY-MM-DD HH:mm。', }, - { - key: 'outImages', - header: '出库实况图路径', - required: false, - note: '选填,ZIP 内 images 目录下的图片路径,多张用 ; 分隔;单张图片最大 100MB。', - }, { key: 'remark', header: '备注', diff --git a/packages/shared/src/enums.ts b/packages/shared/src/enums.ts index c98e55c..cc518cf 100644 --- a/packages/shared/src/enums.ts +++ b/packages/shared/src/enums.ts @@ -71,21 +71,43 @@ export enum QueryResult { export enum ProofStatus { PENDING = 'PENDING', + SUBMITTING = 'SUBMITTING', CONFIRMING = 'CONFIRMING', ONCHAIN = 'ONCHAIN', FAILED = 'FAILED', + UNKNOWN = 'UNKNOWN', } export enum JobType { GEN_CODE = 'GEN_CODE', IMPORT_OUTBOUND = 'IMPORT_OUTBOUND', IMPORT_OUTBOUND_PREVIEW = 'IMPORT_OUTBOUND_PREVIEW', + BATCH_OUTBOUND = 'BATCH_OUTBOUND', WATERMARK = 'WATERMARK', ONCHAIN = 'ONCHAIN', BACKUP = 'BACKUP', RESTORE = 'RESTORE', } +export enum JobItemStatus { + PENDING = 'PENDING', + PROCESSING = 'PROCESSING', + SUCCESS = 'SUCCESS', + FAILED = 'FAILED', + SKIPPED = 'SKIPPED', + UNKNOWN = 'UNKNOWN', +} + +export enum OnchainChunkStatus { + PENDING = 'PENDING', + SUBMITTING = 'SUBMITTING', + CONFIRMING = 'CONFIRMING', + SUCCESS = 'SUCCESS', + PARTIAL = 'PARTIAL', + FAILED = 'FAILED', + UNKNOWN = 'UNKNOWN', +} + export enum JobStatus { PENDING = 'PENDING', PROCESSING = 'PROCESSING', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fb16dec..c692640 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -109,6 +109,9 @@ importers: adm-zip: specifier: ^0.5.18 version: 0.5.18 + archiver: + specifier: 5.3.2 + version: 5.3.2 bcryptjs: specifier: ^2.4.3 version: 2.4.3