feat: 重构追溯码及上链出库流程
This commit is contained in:
@@ -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`);
|
||||
+158
-16
@@ -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;
|
||||
|
||||
+190
-47
@@ -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)
|
||||
|
||||
|
||||
+12
-11
@@ -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>): 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<string>();
|
||||
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<void> {
|
||||
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<void> {
|
||||
|
||||
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<void> {
|
||||
}
|
||||
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} 码)、证书、查询日志与存证。`);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user