From d5764f3b504aca828603ae6adbe400da738aafaa Mon Sep 17 00:00:00 2001 From: super <2903208875@qq.com> Date: Fri, 17 Apr 2026 12:52:16 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E5=8C=B9=E9=85=8D=E3=80=81?= =?UTF-8?q?=E8=B7=9F=E4=BB=B7=E3=80=81=E6=9D=83=E9=99=90=E9=83=A8=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../__pycache__/brand.cpython-312.pyc | Bin 35720 -> 35720 bytes .../nanri/aiimage/common/api/ApiResponse.java | 20 +- .../common/exception/BusinessException.java | 11 + .../exception/GlobalExceptionHandler.java | 4 +- .../common/util/ExcelStreamReader.java | 126 + .../config/DeleteBrandProgressProperties.java | 12 +- .../BrandTaskProgressCacheService.java | 67 +- .../brand/service/BrandTaskService.java | 1 + .../convert/service/ConvertRunService.java | 132 +- .../dedupe/service/DedupeRunService.java | 19 +- .../service/DedupeTotalDataService.java | 78 +- .../controller/DeleteBrandRunController.java | 6 + .../service/DeleteBrandRunService.java | 77 + .../service/DeleteBrandStaleTaskService.java | 77 +- .../service/DeleteBrandTaskCacheService.java | 78 +- .../dto/PermissionMenuCreateRequest.java | 2 + .../dto/PermissionMenuUpdateRequest.java | 2 + .../model/entity/AdminUserEntity.java | 4 + .../model/entity/PermissionMenuEntity.java | 1 + .../model/vo/PermissionMenuItemVo.java | 1 + .../PermissionMenuSchemaInitializer.java | 39 +- .../service/PermissionMenuService.java | 33 + .../controller/PriceTrackController.java | 21 +- .../dto/PriceTrackMatchShopsRequest.java | 17 +- .../dto/PriceTrackSubmitResultRequest.java | 54 +- .../model/vo/PriceTrackCreateTaskVo.java | 13 +- .../model/vo/PriceTrackMatchShopsVo.java | 32 +- .../PriceTrackExcelAssemblyService.java | 54 +- .../pricetrack/service/PriceTrackService.java | 24 +- .../service/PriceTrackTaskService.java | 261 +- .../ProductRiskResolveController.java | 6 + .../service/ProductRiskTaskService.java | 24 +- .../controller/ShopManageController.java | 50 +- .../controller/SkipPriceAsinController.java | 38 +- .../dto/ShopManageGroupCreateRequest.java | 6 +- .../dto/ShopManageGroupUpdateRequest.java | 5 + .../model/dto/SkipPriceAsinCreateRequest.java | 10 +- .../model/entity/ShopManageGroupEntity.java | 2 + .../model/vo/ShopManageGroupItemVo.java | 2 + .../service/ShopManageGroupService.java | 109 +- .../shopkey/service/ShopManageService.java | 39 +- .../shopkey/service/SkipPriceAsinService.java | 90 +- .../controller/ShopMatchController.java | 6 + .../service/ShopMatchTaskCacheService.java | 133 +- .../service/ShopMatchTaskService.java | 45 +- .../split/service/SplitRunService.java | 245 +- .../src/main/resources/application.yml | 12 +- .../resources/db/V24__price_track_tables.sql | 14 + .../db/V25__permission_menu_sort_order.sql | 6 + .../db/V25__shop_manage_group_bind_user.sql | 55 + backend/__pycache__/config.cpython-312.pyc | Bin 1510 -> 1510 bytes .../__pycache__/admin_api.cpython-312.pyc | Bin 67590 -> 84968 bytes backend/blueprints/admin_api.py | 446 ++- backend/utils/__pycache__/db.cpython-312.pyc | Bin 8233 -> 8671 bytes backend/utils/db.py | 8 + backend/web_source/_admin_extracted.js | 2337 +++++++++++++ backend/web_source/_tmp_prefix.js | 2000 +++++++++++ backend/web_source/admin.html | 2993 +++++++++++------ .../brand/components/BrandDeleteBrandTab.vue | 5 +- .../brand/components/BrandPriceTrackTab.vue | 229 +- .../brand/components/BrandProductRiskTab.vue | 13 +- .../brand/components/BrandShopMatchTab.vue | 62 +- frontend-vue/src/shared/api/java-modules.ts | 75 +- 63 files changed, 8858 insertions(+), 1473 deletions(-) create mode 100644 backend-java/src/main/java/com/nanri/aiimage/common/util/ExcelStreamReader.java create mode 100644 backend-java/src/main/resources/db/V24__price_track_tables.sql create mode 100644 backend-java/src/main/resources/db/V25__permission_menu_sort_order.sql create mode 100644 backend-java/src/main/resources/db/V25__shop_manage_group_bind_user.sql create mode 100644 backend/web_source/_admin_extracted.js create mode 100644 backend/web_source/_tmp_prefix.js diff --git a/app/blueprints/__pycache__/brand.cpython-312.pyc b/app/blueprints/__pycache__/brand.cpython-312.pyc index 2fef1f49d257e0cbc1ceffe9abdfb9bf8346ec55..406fa564102af5abb321eb10829ea4556ef7b6a0 100644 GIT binary patch delta 22 ccmeB}&eSoTiTgA!FBbz41mAtIk-N4V087#b5dZ)H delta 22 ccmeB}&eSoTiTgA!FBbz4v`C-b$X(kF07yOtZ2$lO diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/api/ApiResponse.java b/backend-java/src/main/java/com/nanri/aiimage/common/api/ApiResponse.java index a2db9aa..81bd4a7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/common/api/ApiResponse.java +++ b/backend-java/src/main/java/com/nanri/aiimage/common/api/ApiResponse.java @@ -1,13 +1,11 @@ package com.nanri.aiimage.common.api; import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor -@AllArgsConstructor @Schema(description = "统一响应体") public class ApiResponse { @@ -20,6 +18,20 @@ public class ApiResponse { @Schema(description = "响应数据") private T data; + @Schema(description = "业务错误码,成功时可为空") + private Integer code; + + public ApiResponse(boolean success, String message, T data) { + this(success, message, data, null); + } + + public ApiResponse(boolean success, String message, T data, Integer code) { + this.success = success; + this.message = message; + this.data = data; + this.code = code; + } + public static ApiResponse success(T data) { return new ApiResponse<>(true, "操作成功", data); } @@ -31,4 +43,8 @@ public class ApiResponse { public static ApiResponse fail(String message) { return new ApiResponse<>(false, message, null); } + + public static ApiResponse fail(Integer code, String message) { + return new ApiResponse<>(false, message, null, code); + } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/exception/BusinessException.java b/backend-java/src/main/java/com/nanri/aiimage/common/exception/BusinessException.java index 0240697..a4d039a 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/common/exception/BusinessException.java +++ b/backend-java/src/main/java/com/nanri/aiimage/common/exception/BusinessException.java @@ -2,7 +2,18 @@ package com.nanri.aiimage.common.exception; public class BusinessException extends RuntimeException { + private final Integer code; + public BusinessException(String message) { + this(null, message); + } + + public BusinessException(Integer code, String message) { super(message); + this.code = code; + } + + public Integer getCode() { + return code; } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java b/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java index 3512bc8..73d65c6 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java +++ b/backend-java/src/main/java/com/nanri/aiimage/common/exception/GlobalExceptionHandler.java @@ -13,7 +13,9 @@ public class GlobalExceptionHandler { @ExceptionHandler(BusinessException.class) public ApiResponse handleBusinessException(BusinessException ex) { - return ApiResponse.fail(ex.getMessage()); + return ex.getCode() == null + ? ApiResponse.fail(ex.getMessage()) + : ApiResponse.fail(ex.getCode(), ex.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) diff --git a/backend-java/src/main/java/com/nanri/aiimage/common/util/ExcelStreamReader.java b/backend-java/src/main/java/com/nanri/aiimage/common/util/ExcelStreamReader.java new file mode 100644 index 0000000..77725f9 --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/common/util/ExcelStreamReader.java @@ -0,0 +1,126 @@ +package com.nanri.aiimage.common.util; + +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.event.AnalysisEventListener; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; + +public final class ExcelStreamReader { + + private ExcelStreamReader() { + } + + public static void readFirstSheet(File file, SheetRowHandler handler) throws IOException { + try (InputStream inputStream = new FileInputStream(file)) { + readFirstSheet(inputStream, handler); + } + } + + public static void readFirstSheet(InputStream inputStream, SheetRowHandler handler) throws IOException { + runRead(inputStream, false, handler); + } + + public static void readAllSheets(File file, SheetRowHandler handler) throws IOException { + try (InputStream inputStream = new FileInputStream(file)) { + readAllSheets(inputStream, handler); + } + } + + public static void readAllSheets(InputStream inputStream, SheetRowHandler handler) throws IOException { + runRead(inputStream, true, handler); + } + + private static void runRead(InputStream inputStream, boolean readAllSheets, SheetRowHandler handler) throws IOException { + StreamingListener listener = new StreamingListener(handler); + try { + if (readAllSheets) { + EasyExcel.read(inputStream, listener).headRowNumber(1).doReadAll(); + } else { + EasyExcel.read(inputStream, listener).sheet(0).headRowNumber(1).doRead(); + } + } catch (WrappedRuntimeException ex) { + if (ex.getCause() instanceof IOException ioException) { + throw ioException; + } + throw ex; + } + } + + public interface SheetRowHandler { + default void onHeader(String sheetName, Integer sheetNo, Map headerMap) throws Exception { + } + + void onRow(String sheetName, Integer sheetNo, int rowIndex, Map headerMap, Map rowMap) throws Exception; + } + + private static final class StreamingListener extends AnalysisEventListener> { + + private final SheetRowHandler handler; + private Map currentHeaderMap = Map.of(); + + private StreamingListener(SheetRowHandler handler) { + this.handler = handler; + } + + @Override + public void invokeHeadMap(Map headMap, AnalysisContext context) { + Map normalizedHeadMap = new LinkedHashMap<>(); + for (Map.Entry entry : headMap.entrySet()) { + normalizedHeadMap.put(entry.getKey(), entry.getValue()); + } + currentHeaderMap = normalizedHeadMap; + try { + handler.onHeader(sheetName(context), sheetNo(context), currentHeaderMap); + } catch (RuntimeException ex) { + throw ex; + } catch (Exception ex) { + throw new WrappedRuntimeException(ex); + } + } + + @Override + public void invoke(Map data, AnalysisContext context) { + Map normalizedRow = new LinkedHashMap<>(); + for (Map.Entry entry : data.entrySet()) { + normalizedRow.put(entry.getKey(), entry.getValue()); + } + try { + handler.onRow( + sheetName(context), + sheetNo(context), + context.readRowHolder().getRowIndex(), + currentHeaderMap, + normalizedRow + ); + } catch (RuntimeException ex) { + throw ex; + } catch (Exception ex) { + throw new WrappedRuntimeException(ex); + } + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + } + + private String sheetName(AnalysisContext context) { + return context.readSheetHolder() == null ? "" : context.readSheetHolder().getSheetName(); + } + + private Integer sheetNo(AnalysisContext context) { + return context.readSheetHolder() == null ? null : context.readSheetHolder().getSheetNo(); + } + } + + private static final class WrappedRuntimeException extends RuntimeException { + private WrappedRuntimeException(Throwable cause) { + super(cause); + } + } +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java b/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java index b3500b0..b7e4a78 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java +++ b/backend-java/src/main/java/com/nanri/aiimage/config/DeleteBrandProgressProperties.java @@ -18,18 +18,18 @@ public class DeleteBrandProgressProperties { * 商品风险(PRODUCT_RISK_RESOLVE)RUNNING 超时自动收尾/失败,按分钟计算; * 与删除品牌共用同一定时调度。 */ - private long productRiskStaleTimeoutMinutes = 10; - private long productRiskInitialTimeoutMinutes = 10; + private long productRiskStaleTimeoutMinutes = 20; + private long productRiskInitialTimeoutMinutes = 20; /** * Price track RUNNING timeout auto-finalize/fail threshold in minutes. */ - private long priceTrackStaleTimeoutMinutes = 10; - private long priceTrackInitialTimeoutMinutes = 10; + private long priceTrackStaleTimeoutMinutes = 20; + private long priceTrackInitialTimeoutMinutes = 20; /** * Shop match RUNNING timeout auto-finalize/fail threshold in minutes. */ - private long shopMatchStaleTimeoutMinutes = 10; - private long shopMatchInitialTimeoutMinutes = 10; + private long shopMatchStaleTimeoutMinutes = 20; + private long shopMatchInitialTimeoutMinutes = 20; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskProgressCacheService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskProgressCacheService.java index b5bdd07..b7d0612 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskProgressCacheService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskProgressCacheService.java @@ -9,7 +9,11 @@ import com.nanri.aiimage.modules.brand.model.dto.BrandFileAggregateCacheDto; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; +import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.security.MessageDigest; import java.time.Duration; import java.time.Instant; @@ -94,21 +98,28 @@ public class BrandTaskProgressCacheService { public void saveParsedPayload(Long taskId, Object payload) { try { - stringRedisTemplate.opsForValue().set(buildPayloadKey(taskId), objectMapper.writeValueAsString(payload), ttl()); + Files.createDirectories(buildTaskDir(taskId)); + Files.writeString( + buildPayloadFile(taskId), + objectMapper.writeValueAsString(payload), + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.WRITE + ); } catch (Exception ex) { - throw new BusinessException("暂存品牌原始数据失败"); + throw new BusinessException("鏆傚瓨鍝佺墝鍘熷鏁版嵁澶辫触"); } } public T getParsedPayload(Long taskId, TypeReference typeReference) { - String raw = stringRedisTemplate.opsForValue().get(buildPayloadKey(taskId)); - if (raw == null || raw.isBlank()) { + Path payloadFile = buildPayloadFile(taskId); + if (!Files.isRegularFile(payloadFile)) { return null; } try { - return objectMapper.readValue(raw, typeReference); + return objectMapper.readValue(Files.readString(payloadFile), typeReference); } catch (Exception ex) { - throw new BusinessException("读取品牌原始数据失败"); + throw new BusinessException("璇诲彇鍝佺墝鍘熷鏁版嵁澶辫触"); } } @@ -126,7 +137,7 @@ public class BrandTaskProgressCacheService { int finishedFiles = countCompletedFiles(taskId); return new ChunkStoreResult(false, false, finishedFiles, aggregate); } - throw new BusinessException("同一分片重复提交但内容不一致: " + fileUrl + "#" + file.getChunkIndex()); + throw new BusinessException("鍚屼竴鍒嗙墖閲嶅鎻愪氦浣嗗唴瀹逛笉涓€鑷? " + fileUrl + "#" + file.getChunkIndex()); } BrandFileAggregateCacheDto aggregate = getFileAggregate(taskId, fileUrl); @@ -174,7 +185,7 @@ public class BrandTaskProgressCacheService { try { return objectMapper.readValue(json, BrandFileAggregateCacheDto.class); } catch (Exception ex) { - throw new BusinessException("读取品牌文件聚合缓存失败"); + throw new BusinessException("璇诲彇鍝佺墝鏂囦欢鑱氬悎缂撳瓨澶辫触"); } } @@ -209,11 +220,11 @@ public class BrandTaskProgressCacheService { public void delete(Long taskId) { stringRedisTemplate.delete(buildKey(taskId)); - stringRedisTemplate.delete(buildPayloadKey(taskId)); stringRedisTemplate.delete(buildFileAggregateKey(taskId)); stringRedisTemplate.delete(buildCompletedFilesKey(taskId)); stringRedisTemplate.delete(buildFinalizeLockKey(taskId)); stringRedisTemplate.delete(buildLegacyResultKey(taskId)); + deleteTaskDirQuietly(taskId); } public void deleteFileState(Long taskId, String fileUrl) { @@ -236,19 +247,19 @@ public class BrandTaskProgressCacheService { stringRedisTemplate.opsForHash().put(buildFileAggregateKey(taskId), normalizeFileUrl(aggregate.getFileUrl()), objectMapper.writeValueAsString(aggregate)); refreshTaskKey(buildFileAggregateKey(taskId)); } catch (Exception ex) { - throw new BusinessException("暂存品牌文件聚合结果失败"); + throw new BusinessException("鏆傚瓨鍝佺墝鏂囦欢鑱氬悎缁撴灉澶辫触"); } } private void validateChunk(BrandCrawlResultFileDto file) { if (file == null) { - throw new BusinessException("分片不能为空"); + throw new BusinessException("鍒嗙墖涓嶈兘涓虹┖"); } if (file.getChunkIndex() == null || file.getChunkTotal() == null || file.getChunkIndex() <= 0 || file.getChunkTotal() <= 0 || file.getChunkIndex() > file.getChunkTotal()) { - throw new BusinessException("分片参数不合法"); + throw new BusinessException("鍒嗙墖鍙傛暟涓嶅悎娉?"); } if (file.getFileUrl() == null || file.getFileUrl().isBlank()) { - throw new BusinessException("fileUrl 不能为空"); + throw new BusinessException("fileUrl 涓嶈兘涓虹┖"); } } @@ -270,7 +281,7 @@ public class BrandTaskProgressCacheService { private void ensureChunkConsistency(BrandFileAggregateCacheDto aggregate, BrandCrawlResultFileDto file) { if (aggregate.getChunkTotal() != null && file.getChunkTotal() != null && !aggregate.getChunkTotal().equals(file.getChunkTotal())) { - throw new BusinessException("同一文件的 chunkTotal 不一致: " + aggregate.getFileUrl()); + throw new BusinessException("鍚屼竴鏂囦欢鐨?chunkTotal 涓嶄竴鑷? " + aggregate.getFileUrl()); } if (aggregate.getChunkTotal() == null) { aggregate.setChunkTotal(file.getChunkTotal()); @@ -322,7 +333,7 @@ public class BrandTaskProgressCacheService { } return sb.toString(); } catch (Exception ex) { - throw new BusinessException("计算品牌结果分片摘要失败"); + throw new BusinessException("璁$畻鍝佺墝缁撴灉鍒嗙墖鎽樿澶辫触"); } } @@ -340,8 +351,28 @@ public class BrandTaskProgressCacheService { return Duration.ofHours(brandProgressProperties.getTtlHours()); } - private String buildPayloadKey(Long taskId) { - return "brand:task:parsed-payload:" + taskId; + private Path buildTaskDir(Long taskId) { + return Path.of(System.getProperty("java.io.tmpdir"), "brand-task-cache", String.valueOf(taskId)); + } + + private Path buildPayloadFile(Long taskId) { + return buildTaskDir(taskId).resolve("parsed-payload.json"); + } + + private void deleteTaskDirQuietly(Long taskId) { + Path taskDir = buildTaskDir(taskId); + if (!Files.exists(taskDir)) { + return; + } + try (var walk = Files.walk(taskDir)) { + walk.sorted(java.util.Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (IOException ignored) { + } + }); + } catch (IOException ignored) { + } } private String buildFileAggregateKey(Long taskId) { @@ -383,7 +414,7 @@ public class BrandTaskProgressCacheService { } return sb.toString(); } catch (Exception ex) { - throw new BusinessException("生成文件缓存键失败"); + throw new BusinessException("鐢熸垚鏂囦欢缂撳瓨閿け璐?"); } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskService.java index 8b8dbc1..f9e7067 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/brand/service/BrandTaskService.java @@ -327,6 +327,7 @@ public class BrandTaskService { if (deleted == 0) { throw new BusinessException("任务不存在或正在执行中无法删除"); } + brandTaskProgressCacheService.delete(taskId); } public String resolveDownloadUrl(Long taskId) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/convert/service/ConvertRunService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/convert/service/ConvertRunService.java index b524dde..65a01e6 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/convert/service/ConvertRunService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/convert/service/ConvertRunService.java @@ -7,6 +7,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.common.util.ExcelStreamReader; import com.nanri.aiimage.config.StorageProperties; import com.nanri.aiimage.modules.convert.model.dto.ConvertRunRequest; import com.nanri.aiimage.modules.convert.model.dto.UploadedSourceFileDto; @@ -19,15 +20,10 @@ import com.nanri.aiimage.modules.task.mapper.FileTaskMapper; import com.nanri.aiimage.modules.task.model.entity.FileResultEntity; import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity; import lombok.RequiredArgsConstructor; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; import org.springframework.stereotype.Service; +import java.io.BufferedWriter; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -242,14 +238,30 @@ public class ConvertRunService { private List generateOutputFiles(File inputFile, ConvertTemplateEntity templateEntity) throws IOException { List outputFilenames = resolveOutputFilenames(templateEntity); - List rows = buildTxtRows(inputFile, templateEntity); File outputDir = FileUtil.mkdir(FileUtil.file(storageProperties.getLocalTempDir(), "convert-result")); - List generatedFiles = new ArrayList<>(); + Map writers = new LinkedHashMap<>(); for (String outputFilename : outputFilenames) { File outputFile = buildNamedOutputFile(outputDir, outputFilename); - FileUtil.writeLines(rows, outputFile, StandardCharsets.UTF_8); generatedFiles.add(new GeneratedConvertFile(outputFilename, outputFile)); + writers.put(outputFilename, Files.newBufferedWriter(outputFile.toPath(), StandardCharsets.UTF_8)); + } + try { + streamTxtRowsToOutputs(inputFile, templateEntity, writers); + } finally { + IOException closeException = null; + for (BufferedWriter writer : writers.values()) { + try { + writer.close(); + } catch (IOException ex) { + if (closeException == null) { + closeException = ex; + } + } + } + if (closeException != null) { + throw closeException; + } } return generatedFiles; } @@ -266,7 +278,9 @@ public class ConvertRunService { return List.of(outputFilename); } - private List buildTxtRows(File inputFile, ConvertTemplateEntity templateEntity) throws IOException { + private void streamTxtRowsToOutputs(File inputFile, + ConvertTemplateEntity templateEntity, + Map writers) throws IOException { List requiredColumns = readStringList(templateEntity.getRequiredSourceColumnsJson()); List headerColumns = readStringList(templateEntity.getHeaderColumnsJson()); Map fieldMapping = readStringMap(templateEntity.getFieldMappingJson()); @@ -275,65 +289,60 @@ public class ConvertRunService { int blankHeaderRowsAfterSchema = templateEntity.getBlankHeaderRowsAfterSchema() == null ? 0 : templateEntity.getBlankHeaderRowsAfterSchema(); + long batchId = System.currentTimeMillis(); + int[] rowIndex = new int[]{1}; + boolean[] headerRead = new boolean[]{false}; + Map[] headerMapHolder = new Map[]{null}; - DataFormatter formatter = new DataFormatter(); - try (FileInputStream fis = new FileInputStream(inputFile); - Workbook workbook = WorkbookFactory.create(fis)) { - Sheet sheet = workbook.getSheetAt(0); - Row headerRow = sheet.getRow(0); - if (headerRow == null) { - throw new BusinessException("Excel header row is empty."); - } - - Map headerMap = new LinkedHashMap<>(); - for (int i = 0; i < headerRow.getLastCellNum(); i++) { - String value = normalizeCellText(formatter.formatCellValue(headerRow.getCell(i))); - if (!value.isBlank() && !headerMap.containsKey(value)) { - headerMap.put(value, i); + ExcelStreamReader.readFirstSheet(inputFile, new ExcelStreamReader.SheetRowHandler() { + @Override + public void onHeader(String sheetName, Integer sheetNo, Map headerMap) throws Exception { + Map resolvedHeaderMap = new LinkedHashMap<>(); + for (Map.Entry entry : headerMap.entrySet()) { + String value = normalizeCellText(entry.getValue()); + if (!value.isBlank() && !resolvedHeaderMap.containsKey(value)) { + resolvedHeaderMap.put(value, entry.getKey()); + } + } + List missing = requiredColumns.stream() + .filter(column -> !resolvedHeaderMap.containsKey(column)) + .toList(); + if (!missing.isEmpty()) { + throw new BusinessException("Missing required columns: " + String.join(", ", missing)); + } + headerRead[0] = true; + headerMapHolder[0] = resolvedHeaderMap; + for (String line : preambleLines) { + writeLineToAll(writers, line); + } + writeLineToAll(writers, String.join("\t", headerColumns)); + for (int i = 0; i < blankHeaderRowsAfterSchema; i++) { + writeLineToAll(writers, "\t".repeat(Math.max(0, headerColumns.size() - 1))); } } - List missing = requiredColumns.stream() - .filter(column -> !headerMap.containsKey(column)) - .toList(); - if (!missing.isEmpty()) { - throw new BusinessException("Missing required columns: " + String.join(", ", missing)); - } - - List rows = new ArrayList<>(); - rows.addAll(preambleLines); - rows.add(String.join("\t", headerColumns)); - for (int i = 0; i < blankHeaderRowsAfterSchema; i++) { - rows.add("\t".repeat(Math.max(0, headerColumns.size() - 1))); - } - - long batchId = System.currentTimeMillis(); - int rowIndex = 1; - int asinIndex = headerMap.getOrDefault("ASIN", -1); - for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { - Row row = sheet.getRow(rowNum); - if (row == null) { - continue; + @Override + public void onRow(String sheetName, Integer sheetNo, int excelRowIndex, Map headerMap, Map rowMap) throws Exception { + Map resolvedHeaderMap = headerMapHolder[0]; + if (resolvedHeaderMap == null) { + throw new BusinessException("Excel header row is empty."); } - - String asin = asinIndex >= 0 ? normalizeCellText(formatter.formatCellValue(row.getCell(asinIndex))) : ""; + int asinIndex = resolvedHeaderMap.getOrDefault("ASIN", -1); + String asin = asinIndex >= 0 ? normalizeCellText(rowMap.get(asinIndex)) : ""; if (asin.isBlank()) { - continue; + return; } List lineValues = new ArrayList<>(); for (String column : headerColumns) { if ("sku".equals(column)) { - lineValues.add(batchId + "-" + rowIndex); + lineValues.add(batchId + "-" + rowIndex[0]); continue; } if (fieldMapping.containsKey(column)) { String sourceColumn = fieldMapping.get(column); - Integer sourceIndex = headerMap.get(sourceColumn); - String value = sourceIndex == null - ? "" - : normalizeCellText(formatter.formatCellValue(row.getCell(sourceIndex))); - lineValues.add(value); + Integer sourceIndex = resolvedHeaderMap.get(sourceColumn); + lineValues.add(sourceIndex == null ? "" : normalizeCellText(rowMap.get(sourceIndex))); continue; } if (defaults.containsKey(column)) { @@ -343,10 +352,19 @@ public class ConvertRunService { lineValues.add(""); } - rows.add(String.join("\t", lineValues)); - rowIndex++; + writeLineToAll(writers, String.join("\t", lineValues)); + rowIndex[0]++; } - return rows; + }); + if (!headerRead[0]) { + throw new BusinessException("Excel header row is empty."); + } + } + + private void writeLineToAll(Map writers, String line) throws IOException { + for (BufferedWriter writer : writers.values()) { + writer.write(line); + writer.newLine(); } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeRunService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeRunService.java index c82eff7..11a676a 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeRunService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeRunService.java @@ -20,7 +20,7 @@ import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; @@ -232,7 +232,7 @@ public class DedupeRunService { DataFormatter formatter = new DataFormatter(); try (FileInputStream fis = new FileInputStream(inputFile); Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(fis); - XSSFWorkbook outputWorkbook = new XSSFWorkbook()) { + SXSSFWorkbook outputWorkbook = new SXSSFWorkbook(200)) { Sheet sheet = workbook.getSheetAt(0); Row headerRow = sheet.getRow(0); if (headerRow == null) { @@ -275,7 +275,6 @@ public class DedupeRunService { // The preliminary global scan for mainIdHasSubIdMap was removed. // We now determine subset existence contextually (per group) during the main loop. } - List candidateRows = new ArrayList<>(); Set candidateAsinValues = new HashSet<>(); for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { Row row = sheet.getRow(rowNum); @@ -288,7 +287,6 @@ public class DedupeRunService { continue; } } - candidateRows.add(row); if (asinColumnIndex != null) { String asinValue = dedupeTotalDataService.normalizeComparableValueOrBlank(formatter.formatCellValue(row.getCell(asinColumnIndex))); if (!asinValue.isBlank()) { @@ -300,7 +298,17 @@ public class DedupeRunService { Set matchedAsinValues = dedupeTotalDataService.findExistingComparableValues(candidateAsinValues); Set writtenAsinValues = new HashSet<>(); int outputRowIndex = 1; - for (Row row : candidateRows) { + for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { + Row row = sheet.getRow(rowNum); + if (row == null) { + continue; + } + if (idColumnIndex != null) { + String idValue = normalizeCellText(formatter.formatCellValue(row.getCell(idColumnIndex))); + if (!shouldKeepId(idValue, keepIntegerIds, keepUnderscoreIds, keepIntegerMainIdsWhenNoSubIds, sheet, rowNum, idColumnIndex, formatter)) { + continue; + } + } if (asinColumnIndex != null) { String asinValue = dedupeTotalDataService.normalizeComparableValueOrBlank(formatter.formatCellValue(row.getCell(asinColumnIndex))); if (!asinValue.isBlank()) { @@ -324,6 +332,7 @@ public class DedupeRunService { try (FileOutputStream fos = new FileOutputStream(outputFile)) { outputWorkbook.write(fos); } + outputWorkbook.dispose(); } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeTotalDataService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeTotalDataService.java index 33b623c..763b53e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeTotalDataService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeTotalDataService.java @@ -23,7 +23,9 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayInputStream; +import java.io.File; import java.io.InputStream; +import java.nio.file.Files; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -114,9 +116,9 @@ public class DedupeTotalDataService { importProgressMap.put(importId, progress); try { - byte[] fileBytes = file.getBytes(); + File tempFile = saveMultipartToTempFile(file); String filename = file.getOriginalFilename(); - Thread.ofVirtual().start(() -> runImportTask(importId, fileBytes, filename)); + Thread.ofVirtual().start(() -> runImportTask(importId, tempFile, filename)); } catch (Exception e) { importProgressMap.remove(importId); throw new BusinessException("读取上传文件失败"); @@ -150,9 +152,9 @@ public class DedupeTotalDataService { deleteImportProgressMap.put(importId, progress); try { - byte[] fileBytes = file.getBytes(); + File tempFile = saveMultipartToTempFile(file); String filename = file.getOriginalFilename(); - Thread.ofVirtual().start(() -> runDeleteImportTask(importId, fileBytes, filename)); + Thread.ofVirtual().start(() -> runDeleteImportTask(importId, tempFile, filename)); } catch (Exception e) { deleteImportProgressMap.remove(importId); throw new BusinessException("读取上传文件失败"); @@ -211,6 +213,74 @@ public class DedupeTotalDataService { } } + private void runDeleteImportTask(String importId, File tempFile, String filename) { + DedupeTotalDataImportProgressVo progress = deleteImportProgressMap.get(importId); + if (progress == null) { + return; + } + progress.setStatus("running"); + try (InputStream inputStream = Files.newInputStream(tempFile.toPath())) { + DedupeTotalDataImportVo result = deleteFromExcelInternal(inputStream, filename, progress); + progress.setTotalRows(result.getTotalRows()); + progress.setAsinCount(result.getAsinCount()); + progress.setInsertedCount(result.getInsertedCount()); + progress.setSkippedCount(result.getSkippedCount()); + progress.setProcessedRows(result.getTotalRows()); + progress.setStatus("success"); + } catch (Exception e) { + progress.setStatus("failed"); + progress.setErrorMessage(e instanceof BusinessException ? e.getMessage() : "鍒犻櫎 Excel 鍖归厤鏁版嵁澶辫触"); + } finally { + deleteQuietly(tempFile); + } + } + + private void runImportTask(String importId, File tempFile, String filename) { + DedupeTotalDataImportProgressVo progress = importProgressMap.get(importId); + if (progress == null) { + return; + } + progress.setStatus("running"); + try (InputStream inputStream = Files.newInputStream(tempFile.toPath())) { + DedupeTotalDataImportVo result = importFromExcelInternal(inputStream, filename, progress); + progress.setTotalRows(result.getTotalRows()); + progress.setAsinCount(result.getAsinCount()); + progress.setInsertedCount(result.getInsertedCount()); + progress.setSkippedCount(result.getSkippedCount()); + progress.setProcessedRows(result.getTotalRows()); + progress.setStatus("success"); + } catch (Exception e) { + progress.setStatus("failed"); + progress.setErrorMessage(e instanceof BusinessException ? e.getMessage() : "瀵煎叆 Excel 澶辫触"); + } finally { + deleteQuietly(tempFile); + } + } + + private File saveMultipartToTempFile(MultipartFile file) throws Exception { + String suffix = ".xlsx"; + String name = file.getOriginalFilename(); + if (name != null) { + int idx = name.lastIndexOf('.'); + if (idx >= 0) { + suffix = name.substring(idx); + } + } + File tempFile = File.createTempFile("dedupe-total-data-", suffix); + file.transferTo(tempFile); + return tempFile; + } + + private void deleteQuietly(File file) { + if (file == null) { + return; + } + try { + Files.deleteIfExists(file.toPath()); + } catch (Exception ignored) { + } + } + @Transactional public DedupeTotalDataImportVo importFromExcel(MultipartFile file) { if (file == null || file.isEmpty()) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/controller/DeleteBrandRunController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/controller/DeleteBrandRunController.java index b9492bc..45b895c 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/controller/DeleteBrandRunController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/controller/DeleteBrandRunController.java @@ -85,6 +85,12 @@ public class DeleteBrandRunController { return ApiResponse.success(deleteBrandRunService.getTaskDetails(request.getTaskIds())); } + @PostMapping("/tasks/progress/batch") + @Operation(summary = "批量获取删除品牌任务进度摘要", description = "仅返回任务基础状态和行进度摘要,用于前端轮询降载。") + public ApiResponse getTaskProgressBatch(@Valid @RequestBody DeleteBrandTaskBatchRequest request) { + return ApiResponse.success(deleteBrandRunService.getTaskProgress(request.getTaskIds())); + } + @GetMapping("/tasks/{taskId}/deletion-status") @Operation(summary = "获取删除品牌任务删除状态", description = "供 Python/插件按 taskId 查询该删除品牌任务是否已被前端删空。") public ApiResponse getTaskDeletionStatus( diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java index c080b5d..1e357ae 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandRunService.java @@ -544,10 +544,87 @@ public class DeleteBrandRunService { return vo; } + public com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandTaskBatchVo getTaskProgress(java.util.List taskIds) { + com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandTaskBatchVo vo = new com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandTaskBatchVo(); + if (taskIds == null || taskIds.isEmpty()) { + return vo; + } + + java.util.List normalizedTaskIds = taskIds.stream() + .filter(id -> id != null && id > 0) + .distinct() + .limit(50) + .toList(); + if (normalizedTaskIds.isEmpty()) { + return vo; + } + + java.util.Map cachedTasks = deleteBrandTaskCacheService.getTaskCacheBatch(normalizedTaskIds); + java.util.List missingTaskIds = new java.util.ArrayList<>(); + for (Long taskId : normalizedTaskIds) { + if (!cachedTasks.containsKey(taskId)) { + missingTaskIds.add(taskId); + } + } + + java.util.Map taskById = new java.util.LinkedHashMap<>(cachedTasks); + if (!missingTaskIds.isEmpty()) { + java.util.List dbTasks = fileTaskMapper.selectBatchIds(missingTaskIds).stream() + .filter(task -> task != null && MODULE_TYPE.equals(task.getModuleType())) + .toList(); + for (FileTaskEntity dbTask : dbTasks) { + taskById.put(dbTask.getId(), dbTask); + if ("RUNNING".equals(dbTask.getStatus())) { + deleteBrandTaskCacheService.saveTaskCache(dbTask); + } + } + } + + java.util.Map> progressByTaskId = deleteBrandTaskCacheService.getProgressBatch(normalizedTaskIds); + + for (Long taskId : normalizedTaskIds) { + FileTaskEntity task = taskById.get(taskId); + if (task == null) { + vo.getMissingTaskIds().add(taskId); + continue; + } + vo.getItems().add(buildTaskProgressDetail(task, progressByTaskId.get(taskId))); + } + return vo; + } + private DeleteBrandTaskDetailVo buildTaskDetail(FileTaskEntity task) { return buildTaskDetail(task, null); } + private DeleteBrandTaskDetailVo buildTaskProgressDetail(FileTaskEntity task, java.util.Map progress) { + task = refreshIndexedMatchesIfNeeded(task); + DeleteBrandTaskItemVo taskVo = new DeleteBrandTaskItemVo(); + taskVo.setId(task.getId()); + taskVo.setTaskNo(task.getTaskNo()); + taskVo.setStatus(task.getStatus()); + taskVo.setSourceFileCount(task.getSourceFileCount()); + taskVo.setSuccessFileCount(task.getSuccessFileCount()); + taskVo.setFailedFileCount(task.getFailedFileCount()); + taskVo.setErrorMessage(task.getErrorMessage()); + taskVo.setCreatedAt(task.getCreatedAt()); + taskVo.setUpdatedAt(task.getUpdatedAt()); + taskVo.setFinishedAt(task.getFinishedAt()); + if ("SUCCESS".equals(task.getStatus())) { + taskVo.setDownloadUrl(resolveTaskDownloadUrl(task.getId())); + taskVo.setDownloadFilename(resolveTaskDownloadFilename(task.getId())); + } else { + taskVo.setDownloadUrl(null); + taskVo.setDownloadFilename(null); + } + + DeleteBrandTaskDetailVo detail = new DeleteBrandTaskDetailVo(); + detail.setTask(taskVo); + detail.setLine_progress(buildLineProgress(task.getId(), progress)); + detail.setFileProgress(java.util.List.of()); + return detail; + } + private DeleteBrandTaskDetailVo buildTaskDetail(FileTaskEntity task, java.util.Map progress) { task = refreshIndexedMatchesIfNeeded(task); DeleteBrandTaskItemVo taskVo = new DeleteBrandTaskItemVo(); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandStaleTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandStaleTaskService.java index 703a2ce..a003416 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandStaleTaskService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandStaleTaskService.java @@ -17,10 +17,15 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; +import java.util.List; import java.util.Map; @Service @@ -34,6 +39,8 @@ public class DeleteBrandStaleTaskService { private static final String MODULE_TYPE_SHOP_MATCH = "SHOP_MATCH"; private static final Duration STALE_CHECK_LOCK_TTL = Duration.ofMinutes(10); private static final Duration FINALIZE_CHECK_LOCK_TTL = Duration.ofMinutes(10); + private static final Duration TEMP_DIR_CLEANUP_LOCK_TTL = Duration.ofMinutes(10); + private static final Duration TEMP_DIR_RETENTION = Duration.ofHours(48); private final FileTaskMapper fileTaskMapper; private final DeleteBrandTaskCacheService deleteBrandTaskCacheService; @@ -289,7 +296,7 @@ public class DeleteBrandStaleTaskService { log.info("[stale-check] shop-match candidates={} threshold={} timeoutMinutes={} initialThreshold={} initialTimeoutMinutes={}", runningTasks.size(), threshold, minutes, initialThreshold, initialMinutes); for (FileTaskEntity task : runningTasks) { - boolean hasUploadedPayload = !shopMatchTaskCacheService.getAllShopMergedPayload(task.getId()).isEmpty(); + boolean hasUploadedPayload = shopMatchTaskCacheService.hasAnyShopMergedPayload(task.getId()); boolean hasFinishedRows = (task.getSuccessFileCount() != null && task.getSuccessFileCount() > 0) || (task.getFailedFileCount() != null && task.getFailedFileCount() > 0); boolean hasStartedProgress = hasUploadedPayload || hasFinishedRows; @@ -352,6 +359,74 @@ public class DeleteBrandStaleTaskService { } } + @Scheduled(cron = "${aiimage.temp-dir.cleanup-cron:15 */30 * * * *}") + public void cleanupExpiredTempDirs() { + DistributedJobLockService.LockHandle lockHandle = + distributedJobLockService.tryLock("temp-dir:cleanup", TEMP_DIR_CLEANUP_LOCK_TTL); + if (lockHandle == null) { + log.info("[temp-dir-cleanup] skip because another instance holds the distributed lock"); + return; + } + try (lockHandle) { + Instant cutoff = Instant.now().minus(TEMP_DIR_RETENTION); + List dirNames = List.of( + "shop-match-cache", + "brand-task-cache", + "delete-brand-task-cache", + "shop-match-result", + "delete-brand-result", + "product-risk-result", + "price-track-result" + ); + for (String dirName : dirNames) { + cleanupTempRoot(dirName, cutoff); + } + } + } + + private void cleanupTempRoot(String dirName, Instant cutoff) { + Path root = Path.of(System.getProperty("java.io.tmpdir"), dirName); + if (!Files.isDirectory(root)) { + return; + } + try (var stream = Files.list(root)) { + for (Path child : stream.toList()) { + try { + FileTime lastModified = Files.getLastModifiedTime(child); + if (lastModified.toInstant().isAfter(cutoff)) { + continue; + } + deleteRecursively(child); + log.info("[temp-dir-cleanup] deleted expired temp path dir={} path={}", dirName, child); + } catch (Exception ex) { + log.warn("[temp-dir-cleanup] delete failed dir={} path={} msg={}", dirName, child, ex.getMessage()); + } + } + } catch (IOException ex) { + log.warn("[temp-dir-cleanup] scan failed dir={} msg={}", dirName, ex.getMessage()); + } + } + + private void deleteRecursively(Path path) throws IOException { + if (!Files.exists(path)) { + return; + } + try (var walk = Files.walk(path)) { + walk.sorted(java.util.Comparator.reverseOrder()).forEach(item -> { + try { + Files.deleteIfExists(item); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + }); + } catch (RuntimeException ex) { + if (ex.getCause() instanceof IOException ioException) { + throw ioException; + } + throw ex; + } + } + private static final class ProductRiskStaleCheckStats { private int scannedTaskCount; private int finalizedTaskCount; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandTaskCacheService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandTaskCacheService.java index 65a8802..75e38ae 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandTaskCacheService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/deletebrand/service/DeleteBrandTaskCacheService.java @@ -7,6 +7,9 @@ import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.time.Duration; import java.util.concurrent.ConcurrentHashMap; @@ -28,10 +31,17 @@ public class DeleteBrandTaskCacheService { public void saveParsedPayload(Long taskId, Object payload) { try { - stringRedisTemplate.opsForValue().set(buildPayloadKey(taskId), objectMapper.writeValueAsString(payload), Duration.ofHours(PAYLOAD_TTL_HOURS)); + Files.createDirectories(buildTaskDir(taskId)); + Files.writeString( + buildPayloadFile(taskId), + objectMapper.writeValueAsString(payload), + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.WRITE + ); parsedPayloadLocalCache.put(taskId, new LocalParsedPayloadCacheEntry(System.currentTimeMillis(), payload)); } catch (Exception ex) { - throw new BusinessException("暂存删除品牌原始数据失败"); + throw new BusinessException("鏆傚瓨鍒犻櫎鍝佺墝鍘熷鏁版嵁澶辫触"); } } @@ -46,21 +56,21 @@ public class DeleteBrandTaskCacheService { try { return objectMapper.convertValue(cached.value(), typeReference); } catch (Exception ignored) { - // fallthrough to redis + // fall through to file } } - String raw = stringRedisTemplate.opsForValue().get(buildPayloadKey(taskId)); - if (raw == null || raw.isBlank()) { + Path payloadFile = buildPayloadFile(taskId); + if (!Files.isRegularFile(payloadFile)) { parsedPayloadLocalCache.remove(taskId); return null; } try { - T parsed = objectMapper.readValue(raw, typeReference); + T parsed = objectMapper.readValue(Files.readString(payloadFile), typeReference); parsedPayloadLocalCache.put(taskId, new LocalParsedPayloadCacheEntry(now, parsed)); return parsed; } catch (Exception ex) { - throw new BusinessException("读取删除品牌原始数据失败"); + throw new BusinessException("璇诲彇鍒犻櫎鍝佺墝鍘熷鏁版嵁澶辫触"); } } @@ -114,17 +124,17 @@ public class DeleteBrandTaskCacheService { public boolean hasSameResultChunk(Long taskId, String fileIdentity, Integer chunkIndex, Object chunk) { if (chunkIndex == null || chunkIndex <= 0) { - throw new BusinessException("chunkIndex 不合法"); + throw new BusinessException("chunkIndex 涓嶅悎娉?"); } if (fileIdentity == null || fileIdentity.isBlank()) { - throw new BusinessException("fileIdentity 不能为空"); + throw new BusinessException("fileIdentity 涓嶈兘涓虹┖"); } String field = fileIdentity.trim() + "#" + chunkIndex; String chunkJson; try { chunkJson = objectMapper.writeValueAsString(chunk); } catch (Exception ex) { - throw new BusinessException("读取删除品牌结果分片失败"); + throw new BusinessException("璇诲彇鍒犻櫎鍝佺墝缁撴灉鍒嗙墖澶辫触"); } Object existing = stringRedisTemplate.opsForHash().get(buildResultChunksKey(taskId), field); if (chunkJson.equals(existing)) { @@ -137,17 +147,17 @@ public class DeleteBrandTaskCacheService { public boolean mergeResultChunk(Long taskId, String fileIdentity, Integer chunkIndex, Object chunk) { String resultKey = buildResultChunksKey(taskId); if (chunkIndex == null || chunkIndex <= 0) { - throw new BusinessException("chunkIndex 不合法"); + throw new BusinessException("chunkIndex 涓嶅悎娉?"); } if (fileIdentity == null || fileIdentity.isBlank()) { - throw new BusinessException("fileIdentity 不能为空"); + throw new BusinessException("fileIdentity 涓嶈兘涓虹┖"); } String field = fileIdentity.trim() + "#" + chunkIndex; String chunkJson; try { chunkJson = objectMapper.writeValueAsString(chunk); } catch (Exception ex) { - throw new BusinessException("暂存删除品牌结果分片失败"); + throw new BusinessException("鏆傚瓨鍒犻櫎鍝佺墝缁撴灉鍒嗙墖澶辫触"); } Object existing = stringRedisTemplate.opsForHash().get(resultKey, field); if (chunkJson.equals(existing)) { @@ -178,14 +188,16 @@ public class DeleteBrandTaskCacheService { public void delete(Long taskId) { parsedPayloadLocalCache.remove(taskId); - stringRedisTemplate.delete(buildPayloadKey(taskId)); stringRedisTemplate.delete(buildProgressKey(taskId)); stringRedisTemplate.delete(buildResultChunksKey(taskId)); stringRedisTemplate.delete(buildTaskEntityKey(taskId)); + deleteTaskDirQuietly(taskId); } public void saveTaskCache(com.nanri.aiimage.modules.task.model.entity.FileTaskEntity task) { - if (task == null || task.getId() == null) return; + if (task == null || task.getId() == null) { + return; + } try { stringRedisTemplate.opsForValue().set(buildTaskEntityKey(task.getId()), objectMapper.writeValueAsString(task), Duration.ofHours(PAYLOAD_TTL_HOURS)); } catch (Exception ignored) { @@ -194,10 +206,14 @@ public class DeleteBrandTaskCacheService { public java.util.Map getTaskCacheBatch(java.util.List taskIds) { java.util.Map result = new java.util.LinkedHashMap<>(); - if (taskIds == null || taskIds.isEmpty()) return result; + if (taskIds == null || taskIds.isEmpty()) { + return result; + } java.util.List normalized = taskIds.stream().filter(id -> id != null && id > 0).distinct().toList(); - if (normalized.isEmpty()) return result; + if (normalized.isEmpty()) { + return result; + } java.util.List keys = normalized.stream().map(this::buildTaskEntityKey).toList(); java.util.List values = stringRedisTemplate.opsForValue().multiGet(keys); @@ -215,6 +231,30 @@ public class DeleteBrandTaskCacheService { return result; } + private Path buildTaskDir(Long taskId) { + return Path.of(System.getProperty("java.io.tmpdir"), "delete-brand-task-cache", String.valueOf(taskId)); + } + + private Path buildPayloadFile(Long taskId) { + return buildTaskDir(taskId).resolve("parsed-payload.json"); + } + + private void deleteTaskDirQuietly(Long taskId) { + Path taskDir = buildTaskDir(taskId); + if (!Files.exists(taskDir)) { + return; + } + try (var walk = Files.walk(taskDir)) { + walk.sorted(java.util.Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (Exception ignored) { + } + }); + } catch (Exception ignored) { + } + } + private String buildTaskEntityKey(Long taskId) { return "delete-brand:task:entity:" + taskId; } @@ -225,10 +265,6 @@ public class DeleteBrandTaskCacheService { } } - private String buildPayloadKey(Long taskId) { - return "delete-brand:task:parsed-payload:" + taskId; - } - private String buildProgressKey(Long taskId) { return "delete-brand:task:progress:" + taskId; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuCreateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuCreateRequest.java index b40ab05..4cbdfe7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuCreateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuCreateRequest.java @@ -17,4 +17,6 @@ public class PermissionMenuCreateRequest { @NotBlank(message = "菜单路由不能为空") private String routePath; + + private Integer sortOrder; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuUpdateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuUpdateRequest.java index 38ef597..e2b6927 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuUpdateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/dto/PermissionMenuUpdateRequest.java @@ -17,4 +17,6 @@ public class PermissionMenuUpdateRequest { @NotBlank(message = "菜单路由不能为空") private String routePath; + + private Integer sortOrder; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/AdminUserEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/AdminUserEntity.java index b3af65b..9ac7b4e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/AdminUserEntity.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/AdminUserEntity.java @@ -1,6 +1,7 @@ package com.nanri.aiimage.modules.permission.model.entity; import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @@ -11,5 +12,8 @@ public class AdminUserEntity { @TableId(type = IdType.AUTO) private Long id; + private String username; private String role; + @TableField("created_by_id") + private Long createdById; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/PermissionMenuEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/PermissionMenuEntity.java index c8e4262..cbebbf8 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/PermissionMenuEntity.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/entity/PermissionMenuEntity.java @@ -17,5 +17,6 @@ public class PermissionMenuEntity { private String columnKey; private String menuType; private String routePath; + private Integer sortOrder; private LocalDateTime createdAt; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/PermissionMenuItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/PermissionMenuItemVo.java index 875dc87..2db9e38 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/PermissionMenuItemVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/model/vo/PermissionMenuItemVo.java @@ -12,5 +12,6 @@ public class PermissionMenuItemVo { private String columnKey; private String menuType; private String routePath; + private Integer sortOrder; private LocalDateTime createdAt; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java index 3645a2e..41681e7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java @@ -14,10 +14,16 @@ import java.util.List; public class PermissionMenuSchemaInitializer { private final JdbcTemplate jdbcTemplate; + private static final List DEFAULT_ADMIN_MENUS = List.of( - new DefaultAdminMenu("数据去重总数据", "admin_dedupe_total_data", "dedupe-total-data"), - new DefaultAdminMenu("店铺管理", "admin_shop_manage", "shop-manage"), - new DefaultAdminMenu("跳过跟价ASIN", "admin_skip_price_asin", "skip-price-asin") + new DefaultAdminMenu("用户管理", "admin_users", "users", 10), + new DefaultAdminMenu("栏目权限配置", "admin_columns", "columns", 20), + new DefaultAdminMenu("数据去重总数据", "admin_dedupe_total_data", "dedupe-total-data", 30), + new DefaultAdminMenu("店铺密钥管理", "admin_shop_keys", "shop-keys", 40), + new DefaultAdminMenu("店铺管理", "admin_shop_manage", "shop-manage", 50), + new DefaultAdminMenu("跳过跟价ASIN", "admin_skip_price_asin", "skip-price-asin", 60), + new DefaultAdminMenu("查看生成记录", "admin_history", "history", 70), + new DefaultAdminMenu("版本管理", "admin_version", "version", 80) ); @PostConstruct @@ -25,23 +31,19 @@ public class PermissionMenuSchemaInitializer { executeQuietly(""" CREATE TABLE IF NOT EXISTS columns ( id INT AUTO_INCREMENT PRIMARY KEY, - name VARCHAR(128) NOT NULL COMMENT '栏目名', - column_key VARCHAR(64) NOT NULL COMMENT '栏目标识', + name VARCHAR(128) NOT NULL COMMENT '菜单标题', + column_key VARCHAR(64) NOT NULL COMMENT '菜单唯一标识', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uk_column_key (column_key) ) """); executeQuietly("ALTER TABLE columns ADD COLUMN menu_type VARCHAR(20) NOT NULL DEFAULT 'app' COMMENT '菜单类型: app/admin' AFTER column_key"); executeQuietly("ALTER TABLE columns ADD COLUMN route_path VARCHAR(255) NOT NULL DEFAULT '' COMMENT '菜单路由或页面标识' AFTER menu_type"); + executeQuietly("ALTER TABLE columns ADD COLUMN sort_order INT NOT NULL DEFAULT 0 COMMENT '菜单排序' AFTER route_path"); executeQuietly("UPDATE columns SET menu_type = 'app' WHERE menu_type IS NULL OR menu_type = ''"); + executeQuietly("UPDATE columns SET sort_order = id WHERE sort_order IS NULL OR sort_order = 0"); + executeQuietly("ALTER TABLE columns ADD UNIQUE KEY uk_menu_type_route_path (menu_type, route_path)"); ensureDefaultAdminMenus(); - executeQuietly(""" - INSERT INTO columns (name, column_key, menu_type, route_path) - SELECT '店铺管理', 'admin_shop_manage', 'admin', 'shop-manage' - WHERE NOT EXISTS ( - SELECT 1 FROM columns WHERE column_key = 'admin_shop_manage' - ) - """); executeQuietly(""" CREATE TABLE IF NOT EXISTS user_column_permission ( user_id INT NOT NULL, @@ -56,12 +58,17 @@ public class PermissionMenuSchemaInitializer { private void ensureDefaultAdminMenus() { for (DefaultAdminMenu menu : DEFAULT_ADMIN_MENUS) { executeQuietly(""" - INSERT INTO columns (name, column_key, menu_type, route_path) - SELECT '%s', '%s', 'admin', '%s' + INSERT INTO columns (name, column_key, menu_type, route_path, sort_order) + SELECT '%s', '%s', 'admin', '%s', %d WHERE NOT EXISTS ( SELECT 1 FROM columns WHERE column_key = '%s' ) - """.formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.columnKey())); + """.formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.sortOrder(), menu.columnKey())); + executeQuietly(""" + UPDATE columns + SET sort_order = %d + WHERE column_key = '%s' AND (sort_order IS NULL OR sort_order = 0) + """.formatted(menu.sortOrder(), menu.columnKey())); } } @@ -73,6 +80,6 @@ public class PermissionMenuSchemaInitializer { } } - private record DefaultAdminMenu(String name, String columnKey, String routePath) { + private record DefaultAdminMenu(String name, String columnKey, String routePath, int sortOrder) { } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java index a0ef8f0..54ed17e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java @@ -19,6 +19,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; +import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; @@ -41,6 +42,7 @@ public class PermissionMenuService { public List list(String menuType) { LambdaQueryWrapper query = new LambdaQueryWrapper() .eq(isValidMenuType(menuType), PermissionMenuEntity::getMenuType, normalizeMenuType(menuType)) + .orderByAsc(PermissionMenuEntity::getSortOrder) .orderByAsc(PermissionMenuEntity::getId); return permissionMenuMapper.selectList(query).stream() .map(this::toItemVo) @@ -54,12 +56,14 @@ public class PermissionMenuService { String menuType = normalizeMenuTypeRequired(request.getMenuType()); String routePath = normalizeRequired(request.getRoutePath(), "菜单路由不能为空"); ensureUniqueColumnKey(columnKey, null); + ensureUniqueRoutePath(menuType, routePath, null); PermissionMenuEntity entity = new PermissionMenuEntity(); entity.setName(name); entity.setColumnKey(columnKey); entity.setMenuType(menuType); entity.setRoutePath(routePath); + entity.setSortOrder(resolveSortOrder(request.getSortOrder(), null)); permissionMenuMapper.insert(entity); return toItemVo(getMenuById(entity.getId())); } @@ -72,11 +76,13 @@ public class PermissionMenuService { String menuType = normalizeMenuTypeRequired(request.getMenuType()); String routePath = normalizeRequired(request.getRoutePath(), "菜单路由不能为空"); ensureUniqueColumnKey(columnKey, id); + ensureUniqueRoutePath(menuType, routePath, id); entity.setName(name); entity.setColumnKey(columnKey); entity.setMenuType(menuType); entity.setRoutePath(routePath); + entity.setSortOrder(resolveSortOrder(request.getSortOrder(), id)); permissionMenuMapper.updateById(entity); return toItemVo(getMenuById(id)); } @@ -141,6 +147,9 @@ public class PermissionMenuService { .map(menuMap::get) .filter(menu -> menu != null) .filter(menu -> safeMenuType == null || safeMenuType.equals(menu.getMenuType())) + .sorted(Comparator + .comparing(PermissionMenuEntity::getSortOrder, Comparator.nullsLast(Integer::compareTo)) + .thenComparing(PermissionMenuEntity::getId, Comparator.nullsLast(Long::compareTo))) .map(this::toItemVo) .toList(); } @@ -196,6 +205,16 @@ public class PermissionMenuService { } } + private void ensureUniqueRoutePath(String menuType, String routePath, Long excludeId) { + PermissionMenuEntity exists = permissionMenuMapper.selectOne(new LambdaQueryWrapper() + .eq(PermissionMenuEntity::getMenuType, menuType) + .eq(PermissionMenuEntity::getRoutePath, routePath) + .last("LIMIT 1")); + if (exists != null && (excludeId == null || !excludeId.equals(exists.getId()))) { + throw new BusinessException("同一菜单类型下的菜单路由已存在"); + } + } + private String normalizeRequired(String value, String message) { String normalized = value == null ? "" : value.trim(); if (normalized.isEmpty() && !message.isEmpty()) { @@ -247,7 +266,21 @@ public class PermissionMenuService { vo.setColumnKey(entity.getColumnKey()); vo.setMenuType(entity.getMenuType()); vo.setRoutePath(entity.getRoutePath()); + vo.setSortOrder(entity.getSortOrder()); vo.setCreatedAt(entity.getCreatedAt()); return vo; } + + private Integer resolveSortOrder(Integer sortOrder, Long excludeId) { + if (sortOrder != null) { + return sortOrder; + } + PermissionMenuEntity tail = permissionMenuMapper.selectOne(new LambdaQueryWrapper() + .ne(excludeId != null, PermissionMenuEntity::getId, excludeId) + .orderByDesc(PermissionMenuEntity::getSortOrder) + .orderByDesc(PermissionMenuEntity::getId) + .last("LIMIT 1")); + int currentMax = tail == null || tail.getSortOrder() == null ? 0 : tail.getSortOrder(); + return currentMax + 1; + } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/controller/PriceTrackController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/controller/PriceTrackController.java index cf1b812..e0619cb 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/controller/PriceTrackController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/controller/PriceTrackController.java @@ -47,7 +47,8 @@ import java.util.List; @RequestMapping("/api/price-track") @Tag( name = "跟价", - description = "亚马逊跟价处理模块:包含备选店铺、紫鸟匹配、任务创建、Python 回传、任务轮询和结果下载接口。查询类接口需要携带 Query 参数 user_id。") + description = "亚马逊跟价处理模块,包含备选店铺、紫鸟匹配、任务创建、Python 回传、任务轮询和结果下载接口。查询类接口需携带 query 参数 user_id。" +) public class PriceTrackController { private final PriceTrackService priceTrackService; @@ -62,13 +63,13 @@ public class PriceTrackController { } @PostMapping("/candidates") - @Operation(summary = "新增备选店铺", description = "把店铺名称写入当前用户的备选店铺列表,供后续匹配和创建任务使用。") + @Operation(summary = "新增备选店铺", description = "新增一条备选店铺记录,供后续匹配和创建任务使用。") public ApiResponse addCandidate(@Valid @RequestBody PriceTrackCandidateAddRequest request) { return ApiResponse.success(priceTrackService.addCandidate(request)); } @DeleteMapping("/candidates/{id}") - @Operation(summary = "删除备选店铺", description = "删除一条备选店铺记录,id 必须属于当前 user_id。") + @Operation(summary = "删除备选店铺", description = "删除一条备选店铺记录,记录必须属于当前 user_id。") public ApiResponse deleteCandidate( @Parameter(description = "备选店铺记录主键", example = "10") @PathVariable Long id, @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") @@ -107,7 +108,7 @@ public class PriceTrackController { } @GetMapping("/history") - @Operation(summary = "处理记录列表", description = "返回当前用户跟价模块下各店铺结果行,包含运行中和历史记录。") + @Operation(summary = "处理记录列表", description = "返回当前用户跟价模块下各店铺结果记录,包含运行中和历史记录。") public ApiResponse history( @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") @RequestParam("user_id") Long userId) { @@ -115,7 +116,7 @@ public class PriceTrackController { } @DeleteMapping("/history/{resultId}") - @Operation(summary = "删除单条结果记录", description = "删除一条 biz_file_result,并同步重算父任务状态。") + @Operation(summary = "删除单条结果记录", description = "删除一条 biz_file_result 结果记录,并同步重算父任务状态。") public ApiResponse deleteHistory( @Parameter(description = "结果行主键 biz_file_result.id", example = "1001") @PathVariable Long resultId, @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") @@ -131,7 +132,7 @@ public class PriceTrackController { } @DeleteMapping("/tasks/{taskId}") - @Operation(summary = "删除整条任务", description = "删除该任务以及其下属全部结果行,RUNNING、SUCCESS、FAILED 均可。") + @Operation(summary = "删除整条任务", description = "删除该任务以及其下全部结果行,RUNNING、SUCCESS、FAILED 均可删除。") public ApiResponse deleteTask( @Parameter(description = "任务主键 biz_file_task.id", example = "200") @PathVariable Long taskId, @Parameter(name = "user_id", description = "当前用户 ID", required = true, in = ParameterIn.QUERY, example = "1") @@ -151,11 +152,17 @@ public class PriceTrackController { } @PostMapping("/tasks/batch") - @Operation(summary = "批量查询任务详情", description = "按 taskIds 返回任务概要和各店铺结果,供前端轮询使用。") + @Operation(summary = "批量查询任务详情", description = "按 taskIds 返回任务概要和各店铺结果,供前端查询使用。") public ApiResponse tasksBatch(@Valid @RequestBody PriceTrackTaskBatchRequest request) { return ApiResponse.success(priceTrackTaskService.getTaskDetailsBatch(request.getTaskIds())); } + @PostMapping("/tasks/progress/batch") + @Operation(summary = "批量查询任务进度摘要", description = "仅返回任务状态、时间和错误等轻量信息,供前端轮询降载。") + public ApiResponse taskProgressBatch(@Valid @RequestBody PriceTrackTaskBatchRequest request) { + return ApiResponse.success(priceTrackTaskService.getTaskProgressBatch(request.getTaskIds())); + } + @PostMapping("/tasks/{taskId}/result") @Operation(summary = "Python 回传处理结果", description = "同一 taskId 可多次回传。成功时按 countries 生成结果文件,所有店铺进入终态后任务会变为 SUCCESS 或 FAILED。") public ApiResponse submitResult( diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackMatchShopsRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackMatchShopsRequest.java index a743000..c405caf 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackMatchShopsRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackMatchShopsRequest.java @@ -8,13 +8,20 @@ import lombok.Data; import java.util.List; @Data -@Schema(description = "批量匹配店铺请求体:按店铺名查询紫鸟索引,返回是否命中及店铺元数据") +@Schema(description = "Price track match shops request") public class PriceTrackMatchShopsRequest { - @NotNull(message = "user_id不能为空") - @Schema(description = "当前用户 ID,用于审计和数据归属", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") + + @NotNull(message = "userId is required") + @Schema(description = "Current user id", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") private Long userId; - @NotEmpty(message = "店铺列表不能为空") - @Schema(description = "待匹配的店铺名称列表,至少 1 个;返回体 items 与列表顺序对应", requiredMode = Schema.RequiredMode.REQUIRED, example = "[\"店铺甲\",\"店铺乙\"]") + @NotEmpty(message = "shopNames cannot be empty") + @Schema(description = "Shop names to match", requiredMode = Schema.RequiredMode.REQUIRED) private List shopNames; + + @Schema(description = "Selected ASIN file local paths") + private List asinFiles; + + @Schema(description = "Selected country codes") + private List countryCodes; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackSubmitResultRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackSubmitResultRequest.java index 5663628..37c5849 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackSubmitResultRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/dto/PriceTrackSubmitResultRequest.java @@ -7,43 +7,73 @@ import java.util.List; import java.util.Map; @Data -@Schema(description = "Python 回传跟价结果请求体:按店铺提交各国家 ASIN 跟价结果或错误信息") +@Schema(description = "Python submit payload for price track task results") public class PriceTrackSubmitResultRequest { - @Schema(description = "本次回传涉及的店铺列表,至少 1 个,店名需要能和任务结果行匹配", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "Shop result list", requiredMode = Schema.RequiredMode.REQUIRED) private List shops; @Data - @Schema(description = "单个店铺回传结果:成功时提供 countries,失败时可只提供 error") + @Schema(description = "Per-shop submit result") public static class ShopResult { - @Schema(description = "店铺名称,用于和任务内结果行匹配", example = "测试店铺A") + @Schema(description = "Shop name used to match task rows", example = "Test Shop A") private String shopName; - @Schema(description = "按国家分组的结果行,key 为国家代码,例如 DE、UK、FR、IT、ES") + @Schema(description = "Rows grouped by country code, for example DE/UK/FR/IT/ES") private Map> countries; - @Schema(description = "失败时的错误信息;非空则该店铺记为失败") + @Schema(description = "Failure message") private String error; - @Schema(description = "是否成功;false 按失败处理,true 或 null 通常表示结合 countries 判定") + @Schema(description = "Whether the shop finished successfully") private Boolean success; } @Data - @Schema(description = "单条 ASIN 跟价结果") + @Schema(description = "Per-ASIN price track result row") public static class AsinResult { + @Schema(description = "Shop mall name", example = "Amazon.de") + private String shopMallName; + @Schema(description = "ASIN", example = "B0ABCDE123") private String asin; - @Schema(description = "当前店铺价格", example = "19.99") + @Schema(description = "Price", example = "19.99") + private String price; + + @Schema(description = "Recommended price", example = "18.99") + private String recommendedPrice; + + @Schema(description = "Lowest price", example = "18.50") + private String minimumPrice; + + @Schema(description = "First place", example = "Competitor A") + private String firstPlace; + + @Schema(description = "Second place", example = "Competitor B") + private String secondPlace; + + @Schema(description = "Buy box shop name", example = "Shop A") + private String cartShopName; + + @Schema(description = "Price change status", example = "UPDATED") + private String priceChangeStatus; + + @Schema(description = "Modify count", example = "2") + private String modifyCount; + + @Schema(description = "Status", example = "SUCCESS") + private String status; + + @Schema(description = "Legacy current price", example = "19.99") private String currentPrice; - @Schema(description = "竞争对手价格", example = "18.50") + @Schema(description = "Legacy competitor price", example = "18.50") private String competitorPrice; - @Schema(description = "建议动作或跟价动作", example = "LOWER_PRICE") + @Schema(description = "Legacy action", example = "LOWER_PRICE") private String action; - @Schema(description = "该行是否已处理完成") + @Schema(description = "Legacy done flag") private Boolean done; } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCreateTaskVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCreateTaskVo.java index 7acb2a7..1e6b686 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCreateTaskVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackCreateTaskVo.java @@ -4,13 +4,20 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import java.util.List; +import java.util.Map; @Data -@Schema(description = "创建任务响应:包含任务 id 和各店铺的初始结果快照") +@Schema(description = "price track create task response") public class PriceTrackCreateTaskVo { - @Schema(description = "新建任务主键 biz_file_task.id,前端推送队列时需要回传该值", example = "200") + @Schema(description = "task id", example = "200") private Long taskId; - @Schema(description = "各店铺一条初始结果快照,包含 resultId、taskId、店铺信息和初始任务状态") + @Schema(description = "initial task items") private List items; + + @Schema(description = "all skip asins grouped by country") + private Map> skipAsinsByCountry; + + @Schema(description = "parsed asin rows by country") + private Map>> asinRowsByCountry; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackMatchShopsVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackMatchShopsVo.java index e039a29..8e5a86c 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackMatchShopsVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/model/vo/PriceTrackMatchShopsVo.java @@ -5,35 +5,47 @@ import lombok.Data; import java.util.ArrayList; import java.util.List; +import java.util.Map; @Data -@Schema(description = "批量匹配店铺响应") +@Schema(description = "Price track shop match response") public class PriceTrackMatchShopsVo { - @Schema(description = "逐店返回的匹配结果,顺序与请求 shopNames 对应") + + @Schema(description = "Match results in the same order as requested shop names") private List items = new ArrayList<>(); + @Schema(description = "All skip ASINs grouped by country code") + private Map> skipAsinsByCountry; + + @Schema(description = "Parsed asin rows grouped by country code") + private Map>> asinRowsByCountry; + @Data - @Schema(description = "单店匹配结果,同时也是创建任务时 items 的结构") + @Schema(description = "Single matched shop item") public static class PriceTrackShopQueueItem { - @Schema(description = "店铺名称", example = "某某店铺") + + @Schema(description = "Shop name", example = "Demo Shop") private String shopName; - @Schema(description = "紫鸟店铺 ID,未命中时可能为空") + @Schema(description = "Matched shop id") private Object shopId; - @Schema(description = "平台,例如亚马逊", example = "亚马逊") + @Schema(description = "Platform", example = "Amazon") private String platform; - @Schema(description = "公司名称或主体标识") + @Schema(description = "Company name") private String companyName; - @Schema(description = "是否命中紫鸟索引;false 时不可用于创建任务") + @Schema(description = "Whether the shop matched") private Boolean matched; - @Schema(description = "匹配状态码,例如 MATCHED、PENDING、CONFLICT、INDEX_STALE") + @Schema(description = "Match status, such as MATCHED or PENDING") private String matchStatus; - @Schema(description = "人类可读说明,供前端展示") + @Schema(description = "Readable match message") private String matchMessage; + + @Schema(description = "All skip ASINs grouped by country code") + private Map> skipAsins; } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackExcelAssemblyService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackExcelAssemblyService.java index 9fc5029..4b4d03f 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackExcelAssemblyService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackExcelAssemblyService.java @@ -19,7 +19,19 @@ import java.util.Map; @Slf4j public class PriceTrackExcelAssemblyService { - private static final String[] HEADER = {"ASIN", "当前店铺价格", "竞争对手价格", "建议动作", "是否完成"}; + private static final String[] RESULT_HEADER = { + "\u5e97\u94fa\u5546\u57ce\u540d\u79f0", + "ASIN", + "\u4ef7\u683c", + "\u63a8\u8350\u4ef7", + "\u6700\u4f4e\u4ef7", + "\u7b2c\u4e00\u540d", + "\u7b2c\u4e8c\u540d", + "\u8d2d\u7269\u8f66\u5e97\u94fa\u540d", + "\u6539\u4ef7\u60c5\u51b5", + "\u4fee\u6539\u6b21\u6570", + "\u72b6\u6001" + }; public void writeWorkbook(File outputXlsx, Map> countries) { Map> safe = countries == null ? Map.of() : countries; @@ -28,8 +40,8 @@ public class PriceTrackExcelAssemblyService { String sheetName = code.name(); Sheet sheet = wb.createSheet(sheetName); Row headerRow = sheet.createRow(0); - for (int i = 0; i < HEADER.length; i++) { - headerRow.createCell(i).setCellValue(HEADER[i]); + for (int i = 0; i < RESULT_HEADER.length; i++) { + headerRow.createCell(i).setCellValue(RESULT_HEADER[i]); } List rows = safe.getOrDefault(sheetName, List.of()); int rowIdx = 1; @@ -38,20 +50,26 @@ public class PriceTrackExcelAssemblyService { continue; } Row row = sheet.createRow(rowIdx++); - row.createCell(0).setCellValue(item.getAsin() == null ? "" : item.getAsin()); - row.createCell(1).setCellValue(item.getCurrentPrice() == null ? "" : item.getCurrentPrice()); - row.createCell(2).setCellValue(item.getCompetitorPrice() == null ? "" : item.getCompetitorPrice()); - row.createCell(3).setCellValue(item.getAction() == null ? "" : item.getAction()); - row.createCell(4).setCellValue(item.getDone() == null ? "" : String.valueOf(item.getDone())); + row.createCell(0).setCellValue(valueOf(item.getShopMallName())); + row.createCell(1).setCellValue(valueOf(item.getAsin())); + row.createCell(2).setCellValue(firstNonBlank(item.getPrice(), item.getCurrentPrice())); + row.createCell(3).setCellValue(valueOf(item.getRecommendedPrice())); + row.createCell(4).setCellValue(firstNonBlank(item.getMinimumPrice(), item.getCompetitorPrice())); + row.createCell(5).setCellValue(valueOf(item.getFirstPlace())); + row.createCell(6).setCellValue(valueOf(item.getSecondPlace())); + row.createCell(7).setCellValue(valueOf(item.getCartShopName())); + row.createCell(8).setCellValue(firstNonBlank(item.getPriceChangeStatus(), item.getAction())); + row.createCell(9).setCellValue(valueOf(item.getModifyCount())); + row.createCell(10).setCellValue(firstNonBlank(item.getStatus(), item.getDone() == null ? null : String.valueOf(item.getDone()))); } - for (int i = 0; i < HEADER.length; i++) { + for (int i = 0; i < RESULT_HEADER.length; i++) { sheet.autoSizeColumn(i); } } wb.write(fos); } catch (Exception ex) { log.warn("[price-track] write workbook failed: {}", ex.getMessage()); - throw new BusinessException("生成 Excel 失败: " + ex.getMessage()); + throw new BusinessException("鐢熸垚 Excel 澶辫触: " + ex.getMessage()); } } @@ -82,4 +100,20 @@ public class PriceTrackExcelAssemblyService { } return out; } + + private static String valueOf(String value) { + return value == null ? "" : value; + } + + private static String firstNonBlank(String... values) { + if (values == null || values.length == 0) { + return ""; + } + for (String value : values) { + if (value != null && !value.isBlank()) { + return value; + } + } + return ""; + } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackService.java index d9876b7..9f0f285 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackService.java @@ -24,8 +24,10 @@ import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Objects; @Service @@ -40,6 +42,7 @@ public class PriceTrackService { private final ObjectMapper objectMapper; private final ZiniaoShopSwitchService ziniaoShopSwitchService; private final SkipPriceAsinService skipPriceAsinService; + private final PriceTrackTaskService priceTrackTaskService; public List listCandidates(Long userId) { if (userId == null || userId <= 0) { @@ -139,9 +142,22 @@ public class PriceTrackService { throw new BusinessException("shop_names 没有有效店铺名"); } + boolean asinMode = request.getAsinFiles() != null && !request.getAsinFiles().isEmpty(); + Map> skipAsinsByCountry = asinMode + ? new LinkedHashMap<>() + : skipPriceAsinService.listAllSkipAsinsByCountry(); + Map>> asinRowsByCountry = + !asinMode + ? new LinkedHashMap<>() + : priceTrackTaskService.parseMatchAsinRowsByCountry( + request.getAsinFiles(), + request.getCountryCodes()); + PriceTrackMatchShopsVo vo = new PriceTrackMatchShopsVo(); + vo.setSkipAsinsByCountry(skipAsinsByCountry); + vo.setAsinRowsByCountry(asinRowsByCountry); for (String shopName : ordered) { - vo.getItems().add(matchOneShop(shopName)); + vo.getItems().add(matchOneShop(shopName, skipAsinsByCountry)); } return vo; } @@ -198,9 +214,13 @@ public class PriceTrackService { return vo; } - private PriceTrackMatchShopsVo.PriceTrackShopQueueItem matchOneShop(String shopName) { + private PriceTrackMatchShopsVo.PriceTrackShopQueueItem matchOneShop( + String shopName, + Map> skipAsins + ) { PriceTrackMatchShopsVo.PriceTrackShopQueueItem item = new PriceTrackMatchShopsVo.PriceTrackShopQueueItem(); item.setShopName(shopName); + item.setSkipAsins(skipAsins == null ? new LinkedHashMap<>() : new LinkedHashMap<>(skipAsins)); try { ZiniaoShopMatchResultVo match = ziniaoShopSwitchService.findIndexedStoreByName(shopName, false); if (match == null) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskService.java index da04c7e..649d53c 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/pricetrack/service/PriceTrackTaskService.java @@ -4,7 +4,9 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.common.util.ExcelStreamReader; import com.nanri.aiimage.modules.file.service.oss.OssStorageService; +import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode; import com.nanri.aiimage.modules.pricetrack.mapper.PriceTrackShopCandidateMapper; import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackCreateTaskRequest; import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackSubmitResultRequest; @@ -30,12 +32,19 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Locale; @Service @RequiredArgsConstructor @@ -179,8 +188,33 @@ public class PriceTrackTaskService { return batch; } + public PriceTrackTaskBatchVo getTaskProgressBatch(List taskIds) { + PriceTrackTaskBatchVo batch = new PriceTrackTaskBatchVo(); + if (taskIds == null || taskIds.isEmpty()) { + return batch; + } + for (Long taskId : taskIds) { + if (taskId == null || taskId <= 0) { + continue; + } + FileTaskEntity task = fileTaskMapper.selectById(taskId); + if (task == null || !MODULE_TYPE.equals(task.getModuleType())) { + batch.getMissingTaskIds().add(taskId); + continue; + } + PriceTrackTaskDetailVo detail = new PriceTrackTaskDetailVo(); + detail.setTask(toTaskItemVo(task)); + batch.getItems().add(detail); + } + return batch; + } + @Transactional public PriceTrackCreateTaskVo createTask(PriceTrackCreateTaskRequest request) { + if (request.isStatusMode() == request.isAsinMode()) throw new BusinessException("跟价模式必须二选一"); + if (request.isAsinMode() && (request.getAsinFiles() == null || request.getAsinFiles().isEmpty())) { + throw new BusinessException("自定义 ASIN 模式必须上传 ASIN 文件"); + } if (request.getUserId() == null || request.getUserId() <= 0) throw new BusinessException("user_id 不合法"); if (request.getItems() == null || request.getItems().isEmpty()) throw new BusinessException("items 不能为空"); @@ -195,13 +229,14 @@ public class PriceTrackTaskService { } // 汇总店铺名并查询需要跳过的 ASIN - List shopNames = uniqueItems.stream() - .map(PriceTrackMatchShopsVo.PriceTrackShopQueueItem::getShopName) - .filter(s -> s != null && !s.isBlank()) - .distinct() - .toList(); - Map> skipAsinsByShop = skipPriceAsinService.listSkipAsinsByShops(shopNames); - log.info("[price-track] createTask skipAsins shops={}", skipAsinsByShop.keySet()); + Map> skipAsinsByCountry = request.isAsinMode() + ? new LinkedHashMap<>() + : skipPriceAsinService.listAllSkipAsinsByCountry(); + Map>> asinRowsByCountry = request.isAsinMode() + ? parseAsinRowsByCountry(request.getAsinFiles(), request.getCountryCodes()) + : new LinkedHashMap<>(); + log.info("[price-track] createTask skipAsins countries={} asinMode={}", + skipAsinsByCountry.keySet(), request.isAsinMode()); // 创建任务记录 FileTaskEntity task = new FileTaskEntity(); @@ -242,7 +277,8 @@ public class PriceTrackTaskService { ctx.put("statusMode", request.isStatusMode()); ctx.put("asinMode", request.isAsinMode()); ctx.put("countryCodes", request.getCountryCodes()); - ctx.put("skipAsinsByShop", skipAsinsByShop); + ctx.put("skipAsinsByCountry", skipAsinsByCountry); + ctx.put("asinRowsByCountry", asinRowsByCountry); ctx.put("items", uniqueItems); task.setRequestJson(objectMapper.writeValueAsString(ctx)); task.setResultJson(objectMapper.writeValueAsString(snapshot)); @@ -257,6 +293,8 @@ public class PriceTrackTaskService { PriceTrackCreateTaskVo vo = new PriceTrackCreateTaskVo(); vo.setTaskId(task.getId()); vo.setItems(snapshot); + vo.setSkipAsinsByCountry(skipAsinsByCountry); + vo.setAsinRowsByCountry(asinRowsByCountry); return vo; } @@ -272,7 +310,7 @@ public class PriceTrackTaskService { } if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) { log.warn("[price-track] submitResult rejected taskId={} status={}", taskId, task.getStatus()); - throw new BusinessException("任务已结束,拒绝重复提交"); + throw new BusinessException(40901, "任务已结束,拒绝重复提交"); } priceTrackTaskCacheService.touchTaskHeartbeat(taskId); @@ -452,6 +490,211 @@ public class PriceTrackTaskService { } } + public Map>> parseMatchAsinRowsByCountry(List asinFiles, List countryCodes) { + return parseAsinRowsByCountry(asinFiles, countryCodes); + } + + private Map>> parseAsinRowsByCountry(List asinFiles, List countryCodes) { + Map>> merged = new LinkedHashMap<>(); + if (asinFiles == null || asinFiles.isEmpty()) { + return merged; + } + for (String rawPath : asinFiles) { + if (rawPath == null || rawPath.isBlank()) { + continue; + } + File file = new File(rawPath); + if (!file.isFile()) { + throw new BusinessException("ASIN file not found: " + rawPath); + } + String lowerName = file.getName().toLowerCase(Locale.ROOT); + if (lowerName.endsWith(".csv")) { + mergeCountryRows(merged, parseCsvAsinRows(file, countryCodes)); + continue; + } + if (lowerName.endsWith(".xlsx") || lowerName.endsWith(".xls")) { + mergeCountryRows(merged, parseWorkbookAsinRows(file, countryCodes)); + continue; + } + throw new BusinessException("Unsupported ASIN file type: " + file.getName()); + } + return merged; + } + + private Map>> parseWorkbookAsinRows(File file, List countryCodes) { + Map>> out = new LinkedHashMap<>(); + Map[] headerIndexHolder = new Map[]{Map.of()}; + String[] countryCodeHolder = new String[]{null}; + int[] sheetCount = new int[]{0}; + try { + ExcelStreamReader.readAllSheets(file, new ExcelStreamReader.SheetRowHandler() { + @Override + public void onHeader(String sheetName, Integer sheetNo, Map headerMap) { + sheetCount[0]++; + countryCodeHolder[0] = resolveCountryCode(sheetName, countryCodes, false); + headerIndexHolder[0] = buildHeaderIndex(headerMap); + } + + @Override + public void onRow(String sheetName, Integer sheetNo, int rowIndex, Map headerMap, Map rowMap) { + String countryCode = countryCodeHolder[0]; + if (countryCode == null && sheetCount[0] == 1 && countryCodes != null && countryCodes.size() == 1) { + countryCode = countryCodes.get(0); + } + if (countryCode == null) { + return; + } + if (headerIndexHolder[0].isEmpty()) { + return; + } + Map item = extractAsinRow(rowMap, headerIndexHolder[0]); + if (!item.isEmpty()) { + out.computeIfAbsent(countryCode, key -> new ArrayList<>()).add(item); + } + } + }); + } catch (BusinessException ex) { + throw ex; + } catch (Exception ex) { + throw new BusinessException("Failed to parse ASIN workbook"); + } + return out; + } + + private Map>> parseCsvAsinRows(File file, List countryCodes) { + if (countryCodes == null || countryCodes.size() != 1) { + throw new BusinessException("CSV ASIN file requires exactly one selected country"); + } + Map>> out = new LinkedHashMap<>(); + List> rows = out.computeIfAbsent(countryCodes.get(0), key -> new ArrayList<>()); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { + String headerLine = reader.readLine(); + if (headerLine == null) { + return out; + } + List headers = splitCsvLine(headerLine); + Map headerIndex = buildHeaderIndex(headers); + String line; + while ((line = reader.readLine()) != null) { + List values = splitCsvLine(line); + Map item = extractAsinRow(values, headerIndex); + if (!item.isEmpty()) { + rows.add(item); + } + } + } catch (BusinessException ex) { + throw ex; + } catch (Exception ex) { + throw new BusinessException("Failed to parse ASIN csv"); + } + return out; + } + + private void mergeCountryRows(Map>> target, Map>> incoming) { + for (Map.Entry>> entry : incoming.entrySet()) { + target.computeIfAbsent(entry.getKey(), key -> new ArrayList<>()).addAll(entry.getValue()); + } + } + + private String resolveCountryCode(String sheetName, List countryCodes, boolean singleSheetFallback) { + String normalized = normalizeHeaderText(sheetName).toUpperCase(Locale.ROOT); + for (ProductRiskCountryCode code : ProductRiskCountryCode.values()) { + if (code.name().equals(normalized) || normalizeHeaderText(code.getSheetName()).equals(normalizeHeaderText(sheetName))) { + return code.name(); + } + } + if (singleSheetFallback && countryCodes != null && countryCodes.size() == 1) { + return countryCodes.get(0); + } + return null; + } + + private Map buildHeaderIndex(Map headerRow) { + List headers = new ArrayList<>(); + int maxIndex = headerRow.keySet().stream().mapToInt(Integer::intValue).max().orElse(-1); + for (int i = 0; i <= maxIndex; i++) { + headers.add(normalizeCellText(headerRow.get(i))); + } + return buildHeaderIndex(headers); + } + + private Map buildHeaderIndex(List headers) { + Map index = new LinkedHashMap<>(); + for (int i = 0; i < headers.size(); i++) { + String key = mapHeaderKey(headers.get(i)); + if (key != null && !index.containsKey(key)) { + index.put(key, i); + } + } + return index; + } + + private Map extractAsinRow(Map row, Map headerIndex) { + Map item = new LinkedHashMap<>(); + for (Map.Entry entry : headerIndex.entrySet()) { + item.put(entry.getKey(), normalizeCellText(row.get(entry.getValue()))); + } + return isEmptyAsinRow(item) ? Map.of() : item; + } + + private Map extractAsinRow(List values, Map headerIndex) { + Map item = new LinkedHashMap<>(); + for (Map.Entry entry : headerIndex.entrySet()) { + int idx = entry.getValue(); + item.put(entry.getKey(), idx >= 0 && idx < values.size() ? normalizeCellText(values.get(idx)) : ""); + } + return isEmptyAsinRow(item) ? Map.of() : item; + } + + private boolean isEmptyAsinRow(Map row) { + return row.values().stream().allMatch(value -> value == null || value.isBlank()); + } + + private String mapHeaderKey(String rawHeader) { + String header = normalizeHeaderText(rawHeader); + if (header.isEmpty()) { + return null; + } + return switch (header) { + case "店铺商城名称", "shopmallname" -> "shopMallName"; + case "asin" -> "asin"; + case "价格", "price" -> "price"; + case "推荐价", "recommendedprice" -> "recommendedPrice"; + case "最低价", "minimumprice" -> "minimumPrice"; + case "第一名", "firstplace" -> "firstPlace"; + case "第二名", "secondplace" -> "secondPlace"; + case "购物车店铺名", "cartshopname" -> "cartShopName"; + case "改价情况", "pricechangestatus" -> "priceChangeStatus"; + case "修改次数", "modifycount" -> "modifyCount"; + case "状态", "status" -> "status"; + default -> null; + }; + } + + private String normalizeCellText(String value) { + if (value == null) { + return ""; + } + return value.replace("\ufeff", "") + .replace("\u3000", " ") + .replace("\r", " ") + .replace("\n", " ") + .trim() + .replaceAll("\\s+", " "); + } + + private String normalizeHeaderText(String value) { + return normalizeCellText(value) + .replaceAll("\\s+", "") + .toLowerCase(Locale.ROOT); + } + + private List splitCsvLine(String line) { + return Arrays.stream((line == null ? "" : line).split(",", -1)) + .map(String::trim) + .toList(); + } + private List dedupeQueueItems(List raw) { Map byNorm = new LinkedHashMap<>(); for (PriceTrackMatchShopsVo.PriceTrackShopQueueItem item : raw) { diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java index e401ccb..dad10af 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/controller/ProductRiskResolveController.java @@ -159,6 +159,12 @@ public class ProductRiskResolveController { return ApiResponse.success(productRiskTaskService.getTaskDetailsBatch(request.getTaskIds())); } + @PostMapping("/tasks/progress/batch") + @Operation(summary = "批量查询任务进度摘要", description = "仅返回任务状态、时间和错误等轻量信息,供前端轮询降载。") + public ApiResponse taskProgressBatch(@Valid @RequestBody ProductRiskTaskBatchRequest request) { + return ApiResponse.success(productRiskTaskService.getTaskProgressBatch(request.getTaskIds())); + } + @PostMapping("/tasks/{taskId}/result") @Operation( summary = "Python 回传处理结果", diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java index f841151..837fd9f 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/productrisk/service/ProductRiskTaskService.java @@ -147,6 +147,7 @@ public class ProductRiskTaskService { .eq(FileResultEntity::getTaskId, taskId) .eq(FileResultEntity::getModuleType, MODULE_TYPE)); fileTaskMapper.deleteById(taskId); + cleanupTaskCacheIfTerminal(taskId, "DELETE_EMPTY"); } /** @@ -283,6 +284,27 @@ public class ProductRiskTaskService { return batch; } + public ProductRiskTaskBatchVo getTaskProgressBatch(List taskIds) { + ProductRiskTaskBatchVo batch = new ProductRiskTaskBatchVo(); + if (taskIds == null || taskIds.isEmpty()) { + return batch; + } + for (Long taskId : taskIds) { + if (taskId == null || taskId <= 0) { + continue; + } + FileTaskEntity task = fileTaskMapper.selectById(taskId); + if (task == null || !MODULE_TYPE.equals(task.getModuleType())) { + batch.getMissingTaskIds().add(taskId); + continue; + } + ProductRiskTaskDetailVo detail = new ProductRiskTaskDetailVo(); + detail.setTask(toTaskItemVo(task)); + batch.getItems().add(detail); + } + return batch; + } + public String resolveResultDownloadUrl(Long resultId, Long userId) { FileResultEntity entity = fileResultMapper.selectById(resultId); if (entity == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) { @@ -390,7 +412,7 @@ public class ProductRiskTaskService { if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) { log.warn("[product-risk] submitResult rejected taskId={} status={} payloadShopCount={}", taskId, task.getStatus(), request.getShops() == null ? 0 : request.getShops().size()); - throw new BusinessException("任务已结束,拒绝重复提交"); + throw new BusinessException(40901, "任务已结束,拒绝重复提交"); } String oldStatus = task.getStatus(); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java index 4d50b06..1efa657 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/ShopManageController.java @@ -44,7 +44,7 @@ public class ShopManageController { private final ShopManageGroupService shopManageGroupService; @GetMapping - @Operation(summary = "分页查询店铺", description = "支持按分组、店铺名称、创建人进行筛选") + @Operation(summary = "分页查询店铺", description = "支持按分组、店铺名、当前操作者可见范围筛选") @ApiResponses({ @io.swagger.v3.oas.annotations.responses.ApiResponse( responseCode = "200", @@ -56,14 +56,21 @@ public class ShopManageController { @Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize, @Parameter(description = "分组 ID") @RequestParam(required = false) Long groupId, @Parameter(description = "店铺名称") @RequestParam(required = false) String shopName, - @Parameter(description = "创建人用户 ID,普通管理员只传自己") @RequestParam(required = false) Long createdById) { - return ApiResponse.success(shopManageService.page(page, pageSize, groupId, shopName, createdById)); + @Parameter(description = "当前操作人用户ID") @RequestParam(required = false) Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { + return ApiResponse.success(shopManageService.page( + page, + pageSize, + groupId, + shopName, + operatorId, + Boolean.TRUE.equals(superAdmin))); } @PostMapping @Operation(summary = "新增店铺", description = "创建店铺记录,并写入创建人") public ApiResponse create( - @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, @Valid @RequestBody ShopManageCreateRequest request) { return ApiResponse.success("创建成功", @@ -71,10 +78,10 @@ public class ShopManageController { } @PutMapping("/{id}") - @Operation(summary = "更新店铺", description = "按 ID 更新店铺,普通管理员只能修改自己创建的数据") + @Operation(summary = "更新店铺", description = "按 ID 更新店铺") public ApiResponse update( @Parameter(description = "主键 ID", required = true) @PathVariable Long id, - @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, @Valid @RequestBody ShopManageUpdateRequest request) { return ApiResponse.success("更新成功", @@ -82,33 +89,42 @@ public class ShopManageController { } @DeleteMapping("/{id}") - @Operation(summary = "删除店铺", description = "按 ID 删除店铺,普通管理员只能删除自己创建的数据") + @Operation(summary = "删除店铺", description = "按 ID 删除店铺") public ApiResponse delete( @Parameter(description = "主键 ID", required = true) @PathVariable Long id, - @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { shopManageService.delete(id, operatorId, Boolean.TRUE.equals(superAdmin)); return ApiResponse.success("删除成功", null); } @GetMapping("/groups") - @Operation(summary = "查询分组列表", description = "普通管理员只返回自己创建的分组,超级管理员返回全部") + @Operation(summary = "查询分组列表", description = "普通管理员返回当前可访问的分组,超级管理员返回全部") public ApiResponse> listGroups( - @Parameter(description = "创建人用户 ID,普通管理员只传自己") @RequestParam(required = false) Long createdById) { - return ApiResponse.success(shopManageGroupService.list(createdById)); + @Parameter(description = "创建人用户ID") @RequestParam(required = false) Long createdById, + @Parameter(description = "当前操作人用户ID") @RequestParam(required = false) Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { + if (Boolean.TRUE.equals(superAdmin)) { + return ApiResponse.success(shopManageGroupService.list(createdById)); + } + return ApiResponse.success(shopManageGroupService.listAccessible(operatorId, false)); } @PostMapping("/groups") @Operation(summary = "新增分组", description = "创建分组并写入创建人") - public ApiResponse createGroup(@Valid @RequestBody ShopManageGroupCreateRequest request) { - return ApiResponse.success("创建成功", shopManageGroupService.create(request)); + public ApiResponse createGroup( + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, + @Valid @RequestBody ShopManageGroupCreateRequest request) { + return ApiResponse.success("创建成功", + shopManageGroupService.create(request, operatorId, Boolean.TRUE.equals(superAdmin))); } @PutMapping("/groups/{id}") - @Operation(summary = "更新分组", description = "普通管理员只能修改自己创建的分组") + @Operation(summary = "更新分组", description = "普通管理员只能修改自己可访问的分组") public ApiResponse updateGroup( @Parameter(description = "主键 ID", required = true) @PathVariable Long id, - @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, @Valid @RequestBody ShopManageGroupUpdateRequest request) { return ApiResponse.success("更新成功", @@ -116,10 +132,10 @@ public class ShopManageController { } @DeleteMapping("/groups/{id}") - @Operation(summary = "删除分组", description = "普通管理员只能删除自己创建的分组") + @Operation(summary = "删除分组", description = "普通管理员只能删除自己可访问的分组") public ApiResponse deleteGroup( @Parameter(description = "主键 ID", required = true) @PathVariable Long id, - @Parameter(description = "当前操作人用户 ID") @RequestParam Long operatorId, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { shopManageGroupService.delete(id, operatorId, Boolean.TRUE.equals(superAdmin)); return ApiResponse.success("删除成功", null); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java index d840a87..74c951b 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java @@ -1,8 +1,8 @@ package com.nanri.aiimage.modules.shopkey.controller; import com.nanri.aiimage.common.api.ApiResponse; -import com.nanri.aiimage.modules.shopkey.model.dto.SkipPriceAsinCreateRequest; import com.nanri.aiimage.modules.shopkey.model.dto.SkipPriceAsinCountryUpdateRequest; +import com.nanri.aiimage.modules.shopkey.model.dto.SkipPriceAsinCreateRequest; import com.nanri.aiimage.modules.shopkey.model.vo.SkipPriceAsinItemVo; import com.nanri.aiimage.modules.shopkey.model.vo.SkipPriceAsinPageVo; import com.nanri.aiimage.modules.shopkey.service.SkipPriceAsinService; @@ -36,14 +36,27 @@ public class SkipPriceAsinController { @Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize, @Parameter(description = "分组ID") @RequestParam(required = false) Long groupId, @Parameter(description = "店铺名") @RequestParam(required = false) String shopName, - @Parameter(description = "ASIN") @RequestParam(required = false) String asin) { - return ApiResponse.success(skipPriceAsinService.page(page, pageSize, groupId, shopName, asin)); + @Parameter(description = "ASIN") @RequestParam(required = false) String asin, + @Parameter(description = "当前操作人用户ID") @RequestParam(required = false) Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { + return ApiResponse.success(skipPriceAsinService.page( + page, + pageSize, + groupId, + shopName, + asin, + operatorId, + Boolean.TRUE.equals(superAdmin))); } @PostMapping @Operation(summary = "新增或覆盖跳过跟价 ASIN") - public ApiResponse create(@Valid @RequestBody SkipPriceAsinCreateRequest request) { - return ApiResponse.success("保存成功", skipPriceAsinService.createOrUpdate(request)); + public ApiResponse create( + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, + @Valid @RequestBody SkipPriceAsinCreateRequest request) { + return ApiResponse.success("保存成功", + skipPriceAsinService.createOrUpdate(request, operatorId, Boolean.TRUE.equals(superAdmin))); } @PutMapping("/{id}/countries/{country}") @@ -51,16 +64,25 @@ public class SkipPriceAsinController { public ApiResponse updateCountry( @Parameter(description = "主键ID", required = true) @PathVariable Long id, @Parameter(description = "国家编码", required = true) @PathVariable String country, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin, @Valid @RequestBody SkipPriceAsinCountryUpdateRequest request) { - return ApiResponse.success("保存成功", skipPriceAsinService.updateCountry(id, country, request.getAsin())); + return ApiResponse.success("保存成功", skipPriceAsinService.updateCountry( + id, + country, + request.getAsin(), + operatorId, + Boolean.TRUE.equals(superAdmin))); } @DeleteMapping("/{id}/countries/{country}") @Operation(summary = "删除指定国家的跳过跟价 ASIN") public ApiResponse deleteCountry( @Parameter(description = "主键ID", required = true) @PathVariable Long id, - @Parameter(description = "国家编码", required = true) @PathVariable String country) { - skipPriceAsinService.deleteCountry(id, country); + @Parameter(description = "国家编码", required = true) @PathVariable String country, + @Parameter(description = "当前操作人用户ID") @RequestParam Long operatorId, + @Parameter(description = "是否超级管理员") @RequestParam(defaultValue = "false") Boolean superAdmin) { + skipPriceAsinService.deleteCountry(id, country, operatorId, Boolean.TRUE.equals(superAdmin)); return ApiResponse.success("删除成功", null); } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupCreateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupCreateRequest.java index 62d2d5b..236cba7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupCreateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupCreateRequest.java @@ -12,7 +12,11 @@ public class ShopManageGroupCreateRequest { @NotBlank(message = "分组名称不能为空") private String groupName; - @Schema(description = "创建人用户 ID,由后台代理透传", requiredMode = Schema.RequiredMode.REQUIRED) + @Schema(description = "关联用户ID", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "关联用户不能为空") + private Long userId; + + @Schema(description = "创建人用户ID,由后台代理透传", requiredMode = Schema.RequiredMode.REQUIRED) @NotNull(message = "创建人不能为空") private Long createdById; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupUpdateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupUpdateRequest.java index 1469aca..cfa0f92 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupUpdateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/ShopManageGroupUpdateRequest.java @@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.shopkey.model.dto; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import lombok.Data; @Data @@ -10,4 +11,8 @@ public class ShopManageGroupUpdateRequest { @Schema(description = "分组名称", requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank(message = "分组名称不能为空") private String groupName; + + @Schema(description = "关联用户ID", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "关联用户不能为空") + private Long userId; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCreateRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCreateRequest.java index 537d03e..22d666d 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCreateRequest.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/dto/SkipPriceAsinCreateRequest.java @@ -6,6 +6,7 @@ import jakarta.validation.constraints.NotNull; import lombok.Data; import java.util.List; +import java.util.Map; @Data public class SkipPriceAsinCreateRequest { @@ -19,6 +20,13 @@ public class SkipPriceAsinCreateRequest { @NotEmpty(message = "请至少选择一个国家") private List countries; - @NotBlank(message = "ASIN 不能为空") + /** + * 兼容旧请求: 选中的国家共用同一个 ASIN。 + */ private String asin; + + /** + * 新请求: 每个国家对应独立 ASIN,例如 {"DE":"B0...", "UK":"B0..."}。 + */ + private Map asinMappings; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageGroupEntity.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageGroupEntity.java index 623de76..33e4dee 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageGroupEntity.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/entity/ShopManageGroupEntity.java @@ -15,6 +15,8 @@ public class ShopManageGroupEntity { @TableId(type = IdType.AUTO) private Long id; private String groupName; + @TableField("user_id") + private Long userId; @TableField("created_by_id") private Long createdById; private LocalDateTime createdAt; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/ShopManageGroupItemVo.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/ShopManageGroupItemVo.java index a3da49e..3f6de7f 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/ShopManageGroupItemVo.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/model/vo/ShopManageGroupItemVo.java @@ -8,6 +8,8 @@ import java.time.LocalDateTime; public class ShopManageGroupItemVo { private Long id; private String groupName; + private Long userId; + private String username; private LocalDateTime createdAt; private LocalDateTime updatedAt; } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java index 95d2314..b18f70d 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageGroupService.java @@ -2,6 +2,8 @@ package com.nanri.aiimage.modules.shopkey.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.modules.permission.mapper.AdminUserMapper; +import com.nanri.aiimage.modules.permission.model.entity.AdminUserEntity; import com.nanri.aiimage.modules.shopkey.mapper.ShopManageGroupMapper; import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper; import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest; @@ -13,7 +15,9 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; @Service @RequiredArgsConstructor @@ -21,6 +25,7 @@ public class ShopManageGroupService { private final ShopManageGroupMapper groupMapper; private final ShopManageMapper shopManageMapper; + private final AdminUserMapper adminUserMapper; public List list() { return list(null); @@ -35,13 +40,56 @@ public class ShopManageGroupService { .toList(); } + public List listAccessible(Long operatorId, boolean superAdmin) { + if (superAdmin) { + return list(); + } + Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); + return groupMapper.selectList(new LambdaQueryWrapper() + .and(wrapper -> wrapper + .eq(ShopManageGroupEntity::getCreatedById, normalizedOperatorId) + .or() + .eq(ShopManageGroupEntity::getUserId, normalizedOperatorId)) + .orderByAsc(ShopManageGroupEntity::getId)) + .stream() + .map(this::toVo) + .toList(); + } + + public Set listAccessibleGroupIds(Long operatorId, boolean superAdmin) { + if (superAdmin) { + return groupMapper.selectList(new LambdaQueryWrapper() + .select(ShopManageGroupEntity::getId)) + .stream() + .map(ShopManageGroupEntity::getId) + .filter(id -> id != null && id > 0) + .collect(java.util.stream.Collectors.toCollection(LinkedHashSet::new)); + } + Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); + return groupMapper.selectList(new LambdaQueryWrapper() + .select(ShopManageGroupEntity::getId) + .and(wrapper -> wrapper + .eq(ShopManageGroupEntity::getCreatedById, normalizedOperatorId) + .or() + .eq(ShopManageGroupEntity::getUserId, normalizedOperatorId))) + .stream() + .map(ShopManageGroupEntity::getId) + .filter(id -> id != null && id > 0) + .collect(java.util.stream.Collectors.toCollection(LinkedHashSet::new)); + } + @Transactional - public ShopManageGroupItemVo create(ShopManageGroupCreateRequest request) { + public ShopManageGroupItemVo create(ShopManageGroupCreateRequest request, Long operatorId, boolean superAdmin) { Long createdById = normalizePositiveId(request.getCreatedById(), "创建人不能为空"); + AdminUserEntity bindUser = getBindableUser(request.getUserId(), operatorId, superAdmin); String groupName = normalizeRequired(request.getGroupName(), "分组名称不能为空"); - ensureGroupNameUnique(groupName, null, createdById, false); + ensureGroupNameMatchesUser(groupName, bindUser); + ensureGroupNameUnique(groupName, null); + ensureUserUnique(request.getUserId(), null); + ShopManageGroupEntity entity = new ShopManageGroupEntity(); entity.setGroupName(groupName); + entity.setUserId(bindUser.getId()); entity.setCreatedById(createdById); groupMapper.insert(entity); return toVo(getById(entity.getId())); @@ -51,9 +99,14 @@ public class ShopManageGroupService { public ShopManageGroupItemVo update(Long id, Long operatorId, boolean superAdmin, ShopManageGroupUpdateRequest request) { ShopManageGroupEntity entity = getById(id); validateOwnership(entity, operatorId, superAdmin); + AdminUserEntity bindUser = getBindableUser(request.getUserId(), operatorId, superAdmin); String groupName = normalizeRequired(request.getGroupName(), "分组名称不能为空"); - ensureGroupNameUnique(groupName, id, operatorId, superAdmin); + ensureGroupNameMatchesUser(groupName, bindUser); + ensureGroupNameUnique(groupName, id); + ensureUserUnique(bindUser.getId(), id); + entity.setGroupName(groupName); + entity.setUserId(bindUser.getId()); groupMapper.updateById(entity); return toVo(getById(id)); } @@ -84,12 +137,9 @@ public class ShopManageGroupService { return entity; } - private void ensureGroupNameUnique(String groupName, Long excludeId, Long operatorId, boolean superAdmin) { + private void ensureGroupNameUnique(String groupName, Long excludeId) { LambdaQueryWrapper query = new LambdaQueryWrapper() .eq(ShopManageGroupEntity::getGroupName, groupName); - if (!superAdmin) { - query.eq(ShopManageGroupEntity::getCreatedById, normalizePositiveId(operatorId, "操作人不能为空")); - } if (excludeId != null) { query.ne(ShopManageGroupEntity::getId, excludeId); } @@ -99,16 +149,54 @@ public class ShopManageGroupService { } } + private void ensureUserUnique(Long userId, Long excludeId) { + LambdaQueryWrapper query = new LambdaQueryWrapper() + .eq(ShopManageGroupEntity::getUserId, userId); + if (excludeId != null) { + query.ne(ShopManageGroupEntity::getId, excludeId); + } + Long count = groupMapper.selectCount(query); + if (count != null && count > 0) { + throw new BusinessException("该用户已绑定分组"); + } + } + + private void ensureGroupNameMatchesUser(String groupName, AdminUserEntity bindUser) { + if (bindUser == null || bindUser.getUsername() == null || !groupName.equals(bindUser.getUsername().trim())) { + throw new BusinessException("分组名称必须与关联用户名一致"); + } + } + private void validateOwnership(ShopManageGroupEntity entity, Long operatorId, boolean superAdmin) { if (superAdmin) { return; } Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); - if (entity.getCreatedById() == null || !entity.getCreatedById().equals(normalizedOperatorId)) { - throw new BusinessException("只能操作自己创建的分组数据"); + boolean createdBySelf = entity.getCreatedById() != null && entity.getCreatedById().equals(normalizedOperatorId); + boolean boundToSelf = entity.getUserId() != null && entity.getUserId().equals(normalizedOperatorId); + if (!createdBySelf && !boundToSelf) { + throw new BusinessException("只能操作自己有权限的分组数据"); } } + private AdminUserEntity getBindableUser(Long userId, Long operatorId, boolean superAdmin) { + Long normalizedUserId = normalizePositiveId(userId, "关联用户不能为空"); + AdminUserEntity user = adminUserMapper.selectById(normalizedUserId); + if (user == null) { + throw new BusinessException("关联用户不存在"); + } + if (superAdmin) { + return user; + } + Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); + boolean self = user.getId() != null && user.getId().equals(normalizedOperatorId); + boolean createdBySelf = user.getCreatedById() != null && user.getCreatedById().equals(normalizedOperatorId); + if (!self && !createdBySelf) { + throw new BusinessException("只能关联自己可见的用户"); + } + return user; + } + private String normalizeRequired(String value, String message) { String normalized = value == null ? "" : value.trim(); if (normalized.isEmpty()) { @@ -128,6 +216,9 @@ public class ShopManageGroupService { ShopManageGroupItemVo vo = new ShopManageGroupItemVo(); vo.setId(entity.getId()); vo.setGroupName(entity.getGroupName()); + vo.setUserId(entity.getUserId()); + AdminUserEntity bindUser = entity.getUserId() == null ? null : adminUserMapper.selectById(entity.getUserId()); + vo.setUsername(bindUser == null ? "" : (bindUser.getUsername() == null ? "" : bindUser.getUsername())); vo.setCreatedAt(entity.getCreatedAt()); vo.setUpdatedAt(entity.getUpdatedAt()); return vo; diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java index f6ab333..4f72fb6 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/ShopManageService.java @@ -18,6 +18,7 @@ import org.springframework.transaction.annotation.Transactional; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; @Service @RequiredArgsConstructor @@ -27,24 +28,27 @@ public class ShopManageService { private final ShopManageGroupService shopManageGroupService; private final ShopCredentialCryptoService shopCredentialCryptoService; - public ShopManagePageVo page(long page, long pageSize) { - return page(page, pageSize, null, null, null); - } - - public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName) { - return page(page, pageSize, groupId, shopName, null); - } - - public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName, Long createdById) { + public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName, Long operatorId, boolean superAdmin) { long safePage = Math.max(page, 1); long safePageSize = Math.min(Math.max(pageSize, 1), 100); String safeShopName = shopName == null ? "" : shopName.trim(); + Set accessibleGroupIds = superAdmin ? Set.of() : shopManageGroupService.listAccessibleGroupIds(operatorId, false); LambdaQueryWrapper query = new LambdaQueryWrapper() .eq(groupId != null && groupId > 0, ShopManageEntity::getGroupId, groupId) - .eq(createdById != null && createdById > 0, ShopManageEntity::getCreatedById, createdById) .like(!safeShopName.isEmpty(), ShopManageEntity::getShopName, safeShopName) .orderByDesc(ShopManageEntity::getId); + + if (!superAdmin) { + Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); + query.and(wrapper -> { + wrapper.eq(ShopManageEntity::getCreatedById, normalizedOperatorId); + if (!accessibleGroupIds.isEmpty()) { + wrapper.or().in(ShopManageEntity::getGroupId, accessibleGroupIds); + } + }); + } + Long total = shopManageMapper.selectCount(query); List rows = shopManageMapper .selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize)); @@ -90,7 +94,7 @@ public class ShopManageService { @Transactional public ShopManageItemVo update(Long id, Long operatorId, boolean superAdmin, ShopManageUpdateRequest request) { ShopManageEntity entity = getById(id); - validateOwnership(entity, operatorId, superAdmin); + validateGroupAccess(entity, operatorId, superAdmin); ShopManageGroupEntity group = shopManageGroupService.getAccessibleById(request.getGroupId(), operatorId, superAdmin); String shopName = normalizeRequired(request.getShopName(), "店铺名称不能为空"); String mallName = normalizeRequired(request.getMallName(), "商城名称不能为空"); @@ -110,7 +114,7 @@ public class ShopManageService { @Transactional public void delete(Long id, Long operatorId, boolean superAdmin) { ShopManageEntity entity = getById(id); - validateOwnership(entity, operatorId, superAdmin); + validateGroupAccess(entity, operatorId, superAdmin); shopManageMapper.deleteById(entity.getId()); } @@ -146,14 +150,8 @@ public class ShopManageService { return entity; } - private void validateOwnership(ShopManageEntity entity, Long operatorId, boolean superAdmin) { - if (superAdmin) { - return; - } - Long normalizedOperatorId = normalizePositiveId(operatorId, "操作人不能为空"); - if (entity.getCreatedById() == null || !entity.getCreatedById().equals(normalizedOperatorId)) { - throw new BusinessException("只能操作自己创建的店铺数据"); - } + private void validateGroupAccess(ShopManageEntity entity, Long operatorId, boolean superAdmin) { + shopManageGroupService.getAccessibleById(entity.getGroupId(), operatorId, superAdmin); } private String normalizeRequired(String value, String message) { @@ -208,7 +206,6 @@ public class ShopManageService { vo.setMallName(entity.getMallName()); vo.setAccount(entity.getAccount()); String masked = entity.getPassword() == null || entity.getPassword().isBlank() ? "" : "******"; - // 兼容旧前端字段:password 继续返回脱敏值 vo.setPassword(masked); vo.setPasswordMasked(masked); vo.setCreatedAt(entity.getCreatedAt()); diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/SkipPriceAsinService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/SkipPriceAsinService.java index 8a95f2d..0407766 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/SkipPriceAsinService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopkey/service/SkipPriceAsinService.java @@ -28,11 +28,13 @@ public class SkipPriceAsinService { private final SkipPriceAsinMapper skipPriceAsinMapper; private final ShopManageGroupService shopManageGroupService; - public SkipPriceAsinPageVo page(long page, long pageSize, Long groupId, String shopName, String asin) { + public SkipPriceAsinPageVo page(long page, long pageSize, Long groupId, String shopName, String asin, + Long operatorId, boolean superAdmin) { long safePage = Math.max(page, 1); long safePageSize = Math.min(Math.max(pageSize, 1), 100); String safeShopName = normalizeBlank(shopName); String safeAsin = normalizeBlank(asin); + Set accessibleGroupIds = superAdmin ? Set.of() : shopManageGroupService.listAccessibleGroupIds(operatorId, false); LambdaQueryWrapper query = new LambdaQueryWrapper() .eq(groupId != null && groupId > 0, SkipPriceAsinEntity::getGroupId, groupId) @@ -45,6 +47,14 @@ public class SkipPriceAsinService { .or().like(SkipPriceAsinEntity::getAsinEs, safeAsin)) .orderByDesc(SkipPriceAsinEntity::getId); + if (!superAdmin) { + if (accessibleGroupIds.isEmpty()) { + query.eq(SkipPriceAsinEntity::getId, -1L); + } else { + query.in(SkipPriceAsinEntity::getGroupId, accessibleGroupIds); + } + } + Long total = skipPriceAsinMapper.selectCount(query); List rows = skipPriceAsinMapper .selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize)); @@ -64,11 +74,11 @@ public class SkipPriceAsinService { } @Transactional - public SkipPriceAsinItemVo createOrUpdate(SkipPriceAsinCreateRequest request) { - ShopManageGroupEntity group = shopManageGroupService.getById(request.getGroupId()); + public SkipPriceAsinItemVo createOrUpdate(SkipPriceAsinCreateRequest request, Long operatorId, boolean superAdmin) { + ShopManageGroupEntity group = shopManageGroupService.getAccessibleById(request.getGroupId(), operatorId, superAdmin); String shopName = normalizeRequired(request.getShopName(), "店铺名不能为空"); - String asin = normalizeAsin(request.getAsin()); Set countries = normalizeCountries(request.getCountries()); + Map countryAsinMap = normalizeCountryAsinMap(countries, request); SkipPriceAsinEntity entity = skipPriceAsinMapper.selectOne(new LambdaQueryWrapper() .eq(SkipPriceAsinEntity::getGroupId, group.getId()) @@ -80,8 +90,8 @@ public class SkipPriceAsinService { entity.setShopName(shopName); } - for (String country : countries) { - setCountryAsin(entity, country, asin); + for (Map.Entry entry : countryAsinMap.entrySet()) { + setCountryAsin(entity, entry.getKey(), entry.getValue()); } if (entity.getId() == null) { @@ -94,8 +104,9 @@ public class SkipPriceAsinService { } @Transactional - public void deleteCountry(Long id, String country) { + public void deleteCountry(Long id, String country, Long operatorId, boolean superAdmin) { SkipPriceAsinEntity entity = getById(id); + validateGroupAccess(entity, operatorId, superAdmin); String normalizedCountry = normalizeCountry(country); setCountryAsin(entity, normalizedCountry, ""); if (isEmptyRow(entity)) { @@ -106,8 +117,9 @@ public class SkipPriceAsinService { } @Transactional - public SkipPriceAsinItemVo updateCountry(Long id, String country, String asin) { + public SkipPriceAsinItemVo updateCountry(Long id, String country, String asin, Long operatorId, boolean superAdmin) { SkipPriceAsinEntity entity = getById(id); + validateGroupAccess(entity, operatorId, superAdmin); String normalizedCountry = normalizeCountry(country); String normalizedAsin = normalizeAsin(asin); setCountryAsin(entity, normalizedCountry, normalizedAsin); @@ -131,6 +143,10 @@ public class SkipPriceAsinService { return entity; } + private void validateGroupAccess(SkipPriceAsinEntity entity, Long operatorId, boolean superAdmin) { + shopManageGroupService.getAccessibleById(entity.getGroupId(), operatorId, superAdmin); + } + private SkipPriceAsinItemVo toItemVo(SkipPriceAsinEntity entity, String groupName) { SkipPriceAsinItemVo vo = new SkipPriceAsinItemVo(); vo.setId(entity.getId()); @@ -176,6 +192,27 @@ public class SkipPriceAsinService { return normalized; } + private Map normalizeCountryAsinMap(Set countries, SkipPriceAsinCreateRequest request) { + LinkedHashMap normalized = new LinkedHashMap<>(); + Map requestMappings = request.getAsinMappings(); + if (requestMappings != null && !requestMappings.isEmpty()) { + for (String country : countries) { + String asin = requestMappings.get(country); + if (asin == null) { + asin = requestMappings.get(country.toLowerCase(Locale.ROOT)); + } + normalized.put(country, normalizeAsin(asin)); + } + return normalized; + } + + String asin = normalizeAsin(request.getAsin()); + for (String country : countries) { + normalized.put(country, asin); + } + return normalized; + } + private String normalizeCountry(String country) { String normalized = normalizeBlank(country).toUpperCase(Locale.ROOT); if (!SUPPORTED_COUNTRIES.contains(normalized)) { @@ -228,10 +265,6 @@ public class SkipPriceAsinService { && normalizeBlank(entity.getAsinEs()).isEmpty(); } - /** - * 按店铺名列表批量查询跳过跟价ASIN,返回 Map{shopName -> {countryCode -> asin列表}} - * 用于跟价任务创建时将skip ASIN数据下发给Python队列 - */ public Map> listSkipAsinsByShops(List shopNames) { if (shopNames == null || shopNames.isEmpty()) { return Map.of(); @@ -252,4 +285,37 @@ public class SkipPriceAsinService { } return result; } + + public Map> listAllSkipAsinsByCountry() { + List rows = skipPriceAsinMapper.selectList( + new LambdaQueryWrapper() + .orderByDesc(SkipPriceAsinEntity::getId)); + Map> grouped = new LinkedHashMap<>(); + grouped.put("DE", new LinkedHashSet<>()); + grouped.put("UK", new LinkedHashSet<>()); + grouped.put("FR", new LinkedHashSet<>()); + grouped.put("IT", new LinkedHashSet<>()); + grouped.put("ES", new LinkedHashSet<>()); + + for (SkipPriceAsinEntity row : rows) { + addCountryAsin(grouped.get("DE"), row.getAsinDe()); + addCountryAsin(grouped.get("UK"), row.getAsinUk()); + addCountryAsin(grouped.get("FR"), row.getAsinFr()); + addCountryAsin(grouped.get("IT"), row.getAsinIt()); + addCountryAsin(grouped.get("ES"), row.getAsinEs()); + } + + Map> result = new LinkedHashMap<>(); + for (Map.Entry> entry : grouped.entrySet()) { + result.put(entry.getKey(), List.copyOf(entry.getValue())); + } + return result; + } + + private void addCountryAsin(Set bucket, String asin) { + String normalized = normalizeBlank(asin); + if (!normalized.isEmpty()) { + bucket.add(normalized); + } + } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/controller/ShopMatchController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/controller/ShopMatchController.java index 0e4d174..afd9300 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/controller/ShopMatchController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/controller/ShopMatchController.java @@ -163,6 +163,12 @@ public class ShopMatchController { return ApiResponse.success(shopMatchTaskService.getTaskDetailsBatch(request.getTaskIds())); } + @PostMapping("/tasks/progress/batch") + @Operation(summary = "批量查询任务进度摘要", description = "仅返回任务状态、阶段信息与时间等轻量字段,供前端轮询降载。") + public ApiResponse taskProgressBatch(@Valid @RequestBody ProductRiskTaskBatchRequest request) { + return ApiResponse.success(shopMatchTaskService.getTaskProgressBatch(request.getTaskIds())); + } + @PostMapping("/tasks/{taskId}/result") @Operation(summary = "提交匹配结果", description = "Python 可多次分批回传结果;后端会组装文件并在超时场景自动补偿收尾。") public ApiResponse submitResult( diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskCacheService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskCacheService.java index 31a908a..1f98db7 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskCacheService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskCacheService.java @@ -5,10 +5,17 @@ import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchShopPayloadDto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; import java.time.Duration; +import java.util.Comparator; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.Map; @@ -19,21 +26,29 @@ public class ShopMatchTaskCacheService { private static final long PAYLOAD_TTL_HOURS = 24; - private final StringRedisTemplate stringRedisTemplate; private final ObjectMapper objectMapper; public ShopMatchShopPayloadDto getShopMergedPayload(Long taskId, String shopKey) { if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank()) { return null; } - Object raw = stringRedisTemplate.opsForHash().get(buildShopPayloadKey(taskId), shopKey); - if (!(raw instanceof String json) || json.isBlank()) { + Path file = buildShopPayloadFile(taskId, shopKey); + if (!Files.isRegularFile(file)) { return null; } try { - return objectMapper.readValue(json, ShopMatchShopPayloadDto.class); + PayloadFile payloadFile = objectMapper.readValue(Files.readString(file), PayloadFile.class); + if (payloadFile == null || payloadFile.payload == null) { + return null; + } + if (payloadFile.shopKey == null || !shopKey.equals(payloadFile.shopKey)) { + log.warn("[shop-match] payload file shop key mismatch taskId={} shopKey={} storedKey={}", + taskId, shopKey, payloadFile.shopKey); + return null; + } + return payloadFile.payload; } catch (Exception ex) { - throw new BusinessException("读取匹配店铺缓存失败"); + throw new BusinessException("璇诲彇鍖归厤搴楅摵缂撳瓨澶辫触"); } } @@ -42,11 +57,16 @@ public class ShopMatchTaskCacheService { return; } try { - String key = buildShopPayloadKey(taskId); - stringRedisTemplate.opsForHash().put(key, shopKey, objectMapper.writeValueAsString(payload)); - stringRedisTemplate.expire(key, Duration.ofHours(PAYLOAD_TTL_HOURS)); + Files.createDirectories(buildTaskDir(taskId)); + Files.writeString( + buildShopPayloadFile(taskId, shopKey), + objectMapper.writeValueAsString(new PayloadFile(shopKey, payload)), + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.WRITE + ); } catch (Exception ex) { - throw new BusinessException("暂存匹配店铺结果失败"); + throw new BusinessException("鏆傚瓨鍖归厤搴楅摵缁撴灉澶辫触"); } } @@ -54,25 +74,52 @@ public class ShopMatchTaskCacheService { if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank()) { return; } - stringRedisTemplate.opsForHash().delete(buildShopPayloadKey(taskId), shopKey); + try { + Files.deleteIfExists(buildShopPayloadFile(taskId, shopKey)); + } catch (IOException ex) { + log.warn("[shop-match] delete shop payload failed taskId={} shopKey={} msg={}", taskId, shopKey, ex.getMessage()); + } } public Map getAllShopMergedPayload(Long taskId) { try { - Map raw = stringRedisTemplate.opsForHash().entries(buildShopPayloadKey(taskId)); - if (raw == null || raw.isEmpty()) { + Path taskDir = buildTaskDir(taskId); + if (!Files.isDirectory(taskDir)) { return Map.of(); } LinkedHashMap out = new LinkedHashMap<>(); - for (Map.Entry entry : raw.entrySet()) { - if (!(entry.getKey() instanceof String key) || !(entry.getValue() instanceof String val) || val.isBlank()) { - continue; + try (var stream = Files.list(taskDir)) { + for (Path path : stream + .filter(file -> file.getFileName().toString().endsWith(".json")) + .sorted(Comparator.comparing(file -> file.getFileName().toString())) + .toList()) { + PayloadFile payloadFile = objectMapper.readValue(Files.readString(path), PayloadFile.class); + if (payloadFile == null || payloadFile.shopKey == null || payloadFile.shopKey.isBlank() || payloadFile.payload == null) { + continue; + } + out.put(payloadFile.shopKey, payloadFile.payload); } - out.put(key, objectMapper.readValue(val, ShopMatchShopPayloadDto.class)); } return out; } catch (Exception ex) { - throw new BusinessException("读取匹配店铺缓存失败"); + throw new BusinessException("璇诲彇鍖归厤搴楅摵缂撳瓨澶辫触"); + } + } + + public boolean hasAnyShopMergedPayload(Long taskId) { + if (taskId == null || taskId <= 0) { + return false; + } + Path taskDir = buildTaskDir(taskId); + if (!Files.isDirectory(taskDir)) { + return false; + } + try (var stream = Files.list(taskDir)) { + return stream.anyMatch(file -> Files.isRegularFile(file) + && file.getFileName().toString().endsWith(".json")); + } catch (IOException ex) { + log.warn("[shop-match] scan task cache failed taskId={} msg={}", taskId, ex.getMessage()); + return false; } } @@ -81,13 +128,57 @@ public class ShopMatchTaskCacheService { return; } try { - stringRedisTemplate.delete(buildShopPayloadKey(taskId)); + Path taskDir = buildTaskDir(taskId); + if (!Files.exists(taskDir)) { + return; + } + try (var walk = Files.walk(taskDir)) { + walk.sorted(Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (IOException ex) { + log.warn("[shop-match] delete task cache path failed taskId={} path={} msg={}", + taskId, path, ex.getMessage()); + } + }); + } } catch (Exception ex) { log.warn("[shop-match] delete task cache failed taskId={} msg={}", taskId, ex.getMessage()); } } - private String buildShopPayloadKey(Long taskId) { - return "shop-match:task:shop-payload:" + taskId; + public Duration getPayloadTtl() { + return Duration.ofHours(PAYLOAD_TTL_HOURS); + } + + private Path buildTaskDir(Long taskId) { + return Path.of(System.getProperty("java.io.tmpdir"), "shop-match-cache", String.valueOf(taskId)); + } + + private Path buildShopPayloadFile(Long taskId, String shopKey) { + return buildTaskDir(taskId).resolve(hashShopKey(shopKey) + ".json"); + } + + private String hashShopKey(String shopKey) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] bytes = digest.digest(shopKey.trim().getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(bytes); + } catch (Exception ex) { + throw new IllegalStateException("failed to hash shop key", ex); + } + } + + private static class PayloadFile { + public String shopKey; + public ShopMatchShopPayloadDto payload; + + public PayloadFile() { + } + + public PayloadFile(String shopKey, ShopMatchShopPayloadDto payload) { + this.shopKey = shopKey; + this.payload = payload; + } } } diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java index b37b684..c308662 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/shopmatch/service/ShopMatchTaskService.java @@ -185,6 +185,25 @@ public class ShopMatchTaskService { return batch; } + public ProductRiskTaskBatchVo getTaskProgressBatch(List taskIds) { + ProductRiskTaskBatchVo batch = new ProductRiskTaskBatchVo(); + if (taskIds == null || taskIds.isEmpty()) { + return batch; + } + for (Long taskId : taskIds) { + if (taskId == null || taskId <= 0) { + continue; + } + FileTaskEntity task = fileTaskMapper.selectById(taskId); + if (task == null || !MODULE_TYPE.equals(task.getModuleType())) { + batch.getMissingTaskIds().add(taskId); + continue; + } + batch.getItems().add(buildTaskProgressDetail(task)); + } + return batch; + } + public String resolveResultDownloadUrl(Long resultId, Long userId) { FileResultEntity entity = fileResultMapper.selectById(resultId); if (entity == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) { @@ -376,7 +395,7 @@ public class ShopMatchTaskService { throw new BusinessException("任务不存在"); } if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) { - throw new BusinessException("任务已结束,拒绝重复提交"); + throw new BusinessException(40901, "任务已结束,拒绝重复提交"); } List resultRows = fileResultMapper.selectList(new LambdaQueryWrapper() @@ -595,7 +614,11 @@ public class ShopMatchTaskService { task.setSuccessFileCount(ok); task.setFailedFileCount(fail); task.setUpdatedAt(now()); - if (!allDone) { + if (shouldRemainRunningUntilNextStage(task)) { + task.setStatus("RUNNING"); + task.setErrorMessage(null); + task.setFinishedAt(null); + } else if (!allDone) { task.setStatus("RUNNING"); task.setErrorMessage(null); task.setFinishedAt(null); @@ -623,6 +646,18 @@ public class ShopMatchTaskService { } } + private boolean shouldRemainRunningUntilNextStage(FileTaskEntity task) { + ShopMatchCreateTaskRequest request = parseTaskRequestSilently(task); + if (request == null || request.getScheduleTimes() == null || request.getScheduleTimes().isEmpty()) { + return false; + } + Integer activeStageIndex = request.getActiveStageIndex(); + if (activeStageIndex == null) { + return false; + } + return activeStageIndex < request.getScheduleTimes().size() - 1; + } + private ProductRiskTaskDetailVo buildTaskDetail(FileTaskEntity task) { ProductRiskTaskDetailVo detail = new ProductRiskTaskDetailVo(); detail.setTask(toTaskItemVo(task)); @@ -636,6 +671,12 @@ public class ShopMatchTaskService { return detail; } + private ProductRiskTaskDetailVo buildTaskProgressDetail(FileTaskEntity task) { + ProductRiskTaskDetailVo detail = new ProductRiskTaskDetailVo(); + detail.setTask(toTaskItemVo(task)); + return detail; + } + private List buildSnapshotFromDb(Long taskId, String taskStatus) { List rows = fileResultMapper.selectList(new LambdaQueryWrapper() .eq(FileResultEntity::getTaskId, taskId) diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/split/service/SplitRunService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/split/service/SplitRunService.java index 524de90..ad2477e 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/split/service/SplitRunService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/split/service/SplitRunService.java @@ -5,6 +5,7 @@ import cn.hutool.core.util.IdUtil; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.nanri.aiimage.common.exception.BusinessException; +import com.nanri.aiimage.common.util.ExcelStreamReader; import com.nanri.aiimage.config.StorageProperties; import com.nanri.aiimage.modules.file.service.oss.OssStorageService; import com.nanri.aiimage.modules.split.model.dto.SplitRunRequest; @@ -17,20 +18,14 @@ import com.nanri.aiimage.modules.task.mapper.FileTaskMapper; import com.nanri.aiimage.modules.task.model.entity.FileResultEntity; import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity; import lombok.RequiredArgsConstructor; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.IOException; import java.nio.file.Files; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @@ -217,84 +212,119 @@ public class SplitRunService { String originalFilename, SplitRunRequest request ) throws Exception { - DataFormatter formatter = new DataFormatter(); - try (FileInputStream fis = new FileInputStream(inputFile); - Workbook workbook = WorkbookFactory.create(fis)) { - Sheet sheet = workbook.getSheetAt(0); - Row headerRow = sheet.getRow(0); - if (headerRow == null) { - throw new BusinessException("Excel header row is empty."); - } - - Map headerMap = buildHeaderMap(headerRow, formatter); - List missing = request.getSelectedColumns().stream() - .filter(column -> !headerMap.containsKey(column)) - .toList(); - if (!missing.isEmpty()) { - throw new BusinessException("Missing required columns: " + String.join(", ", missing)); - } - - List> rowsData = new ArrayList<>(); - for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { - Row row = sheet.getRow(rowNum); - if (row == null) { - continue; - } - List projected = new ArrayList<>(); - for (String column : request.getSelectedColumns()) { - Integer sourceIndex = headerMap.get(column); - String value = sourceIndex == null - ? "" - : normalizeCellText(formatter.formatCellValue(row.getCell(sourceIndex))); - projected.add(value); - } - rowsData.add(projected); - } - - if (rowsData.isEmpty()) { - throw new BusinessException("No data rows available for splitting."); - } - - List>> chunks = buildChunks(rowsData, request); - File outputDir = FileUtil.mkdir(FileUtil.file(storageProperties.getLocalTempDir(), "split-result")); - String sourceStem = FileUtil.mainName(originalFilename); - List results = new ArrayList<>(); - - for (int i = 0; i < chunks.size(); i++) { - File outputFile = buildNamedOutputFile(outputDir, sourceStem + "_split_" + (i + 1) + ".xlsx"); - try (XSSFWorkbook outputWorkbook = new XSSFWorkbook()) { - Sheet outputSheet = outputWorkbook.createSheet(sheet.getSheetName()); - Row outputHeaderRow = outputSheet.createRow(0); - for (int colIndex = 0; colIndex < request.getSelectedColumns().size(); colIndex++) { - outputHeaderRow.createCell(colIndex).setCellValue(request.getSelectedColumns().get(colIndex)); - } - int outputRowIndex = 1; - for (List rowValues : chunks.get(i)) { - Row outputRow = outputSheet.createRow(outputRowIndex++); - for (int colIndex = 0; colIndex < rowValues.size(); colIndex++) { - outputRow.createCell(colIndex).setCellValue(rowValues.get(colIndex)); - } - } - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - outputWorkbook.write(fos); - } - } - results.add(new SplitChunkResult(outputFile, chunks.get(i).size())); - } - - return results; + CountResult countResult = countSplitRows(inputFile, request.getSelectedColumns()); + if (countResult.rowCount() <= 0) { + throw new BusinessException("No data rows available for splitting."); } + + List chunkSizes = buildChunkSizes(countResult.rowCount(), request); + File outputDir = FileUtil.mkdir(FileUtil.file(storageProperties.getLocalTempDir(), "split-result")); + String sourceStem = FileUtil.mainName(originalFilename); + List results = new ArrayList<>(); + List writers = new ArrayList<>(); + try { + for (int i = 0; i < chunkSizes.size(); i++) { + File outputFile = buildNamedOutputFile(outputDir, sourceStem + "_split_" + (i + 1) + ".xlsx"); + ChunkWriter writer = new ChunkWriter(outputFile, countResult.sheetName(), request.getSelectedColumns(), chunkSizes.get(i)); + writers.add(writer); + results.add(new SplitChunkResult(outputFile, chunkSizes.get(i))); + } + + Map[] headerMapHolder = new Map[]{null}; + int[] chunkIndex = new int[]{0}; + ExcelStreamReader.readFirstSheet(inputFile, new ExcelStreamReader.SheetRowHandler() { + @Override + public void onHeader(String sheetName, Integer sheetNo, Map headerMap) { + Map resolvedHeaderMap = buildHeaderMap(headerMap); + List missing = request.getSelectedColumns().stream() + .filter(column -> !resolvedHeaderMap.containsKey(column)) + .toList(); + if (!missing.isEmpty()) { + throw new BusinessException("Missing required columns: " + String.join(", ", missing)); + } + headerMapHolder[0] = resolvedHeaderMap; + } + + @Override + public void onRow(String sheetName, Integer sheetNo, int rowIndex, Map headerMap, Map rowMap) throws Exception { + if (chunkIndex[0] >= writers.size()) { + return; + } + Map resolvedHeaderMap = headerMapHolder[0]; + if (resolvedHeaderMap == null) { + throw new BusinessException("Excel header row is empty."); + } + List projected = new ArrayList<>(); + for (String column : request.getSelectedColumns()) { + Integer sourceIndex = resolvedHeaderMap.get(column); + projected.add(sourceIndex == null ? "" : normalizeCellText(rowMap.get(sourceIndex))); + } + ChunkWriter writer = writers.get(chunkIndex[0]); + writer.writeRow(projected); + if (writer.isFull()) { + chunkIndex[0]++; + } + } + }); + } finally { + IOException closeException = null; + for (ChunkWriter writer : writers) { + try { + writer.close(); + } catch (IOException ex) { + if (closeException == null) { + closeException = ex; + } + } + } + if (closeException != null) { + throw closeException; + } + } + + return results; } - private Map buildHeaderMap(Row headerRow, DataFormatter formatter) { + private CountResult countSplitRows(File inputFile, List selectedColumns) throws IOException { + int[] rowCount = new int[]{0}; + String[] sheetName = new String[]{"Sheet1"}; + boolean[] headerRead = new boolean[]{false}; + ExcelStreamReader.readFirstSheet(inputFile, new ExcelStreamReader.SheetRowHandler() { + @Override + public void onHeader(String currentSheetName, Integer sheetNo, Map headerMap) { + Map resolvedHeaderMap = buildHeaderMap(headerMap); + List missing = selectedColumns.stream() + .filter(column -> !resolvedHeaderMap.containsKey(column)) + .toList(); + if (!missing.isEmpty()) { + throw new BusinessException("Missing required columns: " + String.join(", ", missing)); + } + sheetName[0] = currentSheetName == null || currentSheetName.isBlank() ? "Sheet1" : currentSheetName; + headerRead[0] = true; + } + + @Override + public void onRow(String currentSheetName, Integer sheetNo, int rowIndex, Map headerMap, Map rowMap) { + if (!headerRead[0]) { + throw new BusinessException("Excel header row is empty."); + } + rowCount[0]++; + } + }); + if (!headerRead[0]) { + throw new BusinessException("Excel header row is empty."); + } + return new CountResult(rowCount[0], sheetName[0]); + } + + private Map buildHeaderMap(Map headerRow) { Map headerMap = new HashMap<>(); - for (int i = 0; i < headerRow.getLastCellNum(); i++) { - Cell cell = headerRow.getCell(i); - String value = normalizeHeaderName(cell == null ? null : formatter.formatCellValue(cell)); + for (Map.Entry entry : headerRow.entrySet()) { + String value = normalizeHeaderName(entry.getValue()); if (value.isBlank() || headerMap.containsKey(value)) { continue; } - headerMap.put(value, i); + headerMap.put(value, entry.getKey()); if (HEADER_STOP_COLUMN.equals(value)) { break; } @@ -302,14 +332,13 @@ public class SplitRunService { return headerMap; } - private List>> buildChunks(List> rowsData, SplitRunRequest request) { - int totalRows = rowsData.size(); - List>> chunks = new ArrayList<>(); + private List buildChunkSizes(int totalRows, SplitRunRequest request) { + List chunks = new ArrayList<>(); if (SPLIT_MODE_ROWS_PER_FILE.equals(request.getSplitMode())) { int chunkSize = request.getRowsPerFile(); for (int i = 0; i < totalRows; i += chunkSize) { - chunks.add(rowsData.subList(i, Math.min(i + chunkSize, totalRows))); + chunks.add(Math.min(chunkSize, totalRows - i)); } return chunks; } @@ -317,12 +346,8 @@ public class SplitRunService { int actualParts = Math.min(request.getParts(), totalRows); int base = totalRows / actualParts; int remainder = totalRows % actualParts; - int start = 0; for (int i = 0; i < actualParts; i++) { - int size = base + (i < remainder ? 1 : 0); - int end = start + size; - chunks.add(rowsData.subList(start, end)); - start = end; + chunks.add(base + (i < remainder ? 1 : 0)); } return chunks; } @@ -448,4 +473,48 @@ public class SplitRunService { private record TaskSplitChunkResult(String relativePath, String sourceFilename, File outputFile, int rowCount) { } + + private record CountResult(int rowCount, String sheetName) { + } + + private static final class ChunkWriter implements AutoCloseable { + private final File outputFile; + private final SXSSFWorkbook workbook; + private final org.apache.poi.ss.usermodel.Sheet sheet; + private final int rowLimit; + private int writtenRows; + + private ChunkWriter(File outputFile, String sheetName, List columns, int rowLimit) { + this.outputFile = outputFile; + this.rowLimit = rowLimit; + this.workbook = new SXSSFWorkbook(200); + this.sheet = workbook.createSheet(sheetName == null || sheetName.isBlank() ? "Sheet1" : sheetName); + org.apache.poi.ss.usermodel.Row headerRow = sheet.createRow(0); + for (int i = 0; i < columns.size(); i++) { + headerRow.createCell(i).setCellValue(columns.get(i)); + } + } + + private void writeRow(List values) { + org.apache.poi.ss.usermodel.Row outputRow = sheet.createRow(writtenRows + 1); + for (int colIndex = 0; colIndex < values.size(); colIndex++) { + outputRow.createCell(colIndex).setCellValue(values.get(colIndex)); + } + writtenRows++; + } + + private boolean isFull() { + return writtenRows >= rowLimit; + } + + @Override + public void close() throws IOException { + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + workbook.write(fos); + } finally { + workbook.dispose(); + workbook.close(); + } + } + } } diff --git a/backend-java/src/main/resources/application.yml b/backend-java/src/main/resources/application.yml index 066b61c..26247eb 100644 --- a/backend-java/src/main/resources/application.yml +++ b/backend-java/src/main/resources/application.yml @@ -82,12 +82,12 @@ aiimage: heartbeat-timeout-minutes: ${AIIMAGE_DELETE_BRAND_HEARTBEAT_TIMEOUT_MINUTES:15} stale-check-cron: ${AIIMAGE_DELETE_BRAND_STALE_CHECK_CRON:*/30 * * * * *} finalize-check-cron: ${AIIMAGE_DELETE_BRAND_FINALIZE_CHECK_CRON:30 */2 * * * *} - product-risk-stale-timeout-minutes: ${AIIMAGE_PRODUCT_RISK_STALE_TIMEOUT_MINUTES:10} - product-risk-initial-timeout-minutes: ${AIIMAGE_PRODUCT_RISK_INITIAL_TIMEOUT_MINUTES:10} - price-track-stale-timeout-minutes: ${AIIMAGE_PRICE_TRACK_STALE_TIMEOUT_MINUTES:10} - price-track-initial-timeout-minutes: ${AIIMAGE_PRICE_TRACK_INITIAL_TIMEOUT_MINUTES:10} - shop-match-stale-timeout-minutes: ${AIIMAGE_SHOP_MATCH_STALE_TIMEOUT_MINUTES:10} - shop-match-initial-timeout-minutes: ${AIIMAGE_SHOP_MATCH_INITIAL_TIMEOUT_MINUTES:10} + product-risk-stale-timeout-minutes: ${AIIMAGE_PRODUCT_RISK_STALE_TIMEOUT_MINUTES:20} + product-risk-initial-timeout-minutes: ${AIIMAGE_PRODUCT_RISK_INITIAL_TIMEOUT_MINUTES:20} + price-track-stale-timeout-minutes: ${AIIMAGE_PRICE_TRACK_STALE_TIMEOUT_MINUTES:20} + price-track-initial-timeout-minutes: ${AIIMAGE_PRICE_TRACK_INITIAL_TIMEOUT_MINUTES:20} + shop-match-stale-timeout-minutes: ${AIIMAGE_SHOP_MATCH_STALE_TIMEOUT_MINUTES:20} + shop-match-initial-timeout-minutes: ${AIIMAGE_SHOP_MATCH_INITIAL_TIMEOUT_MINUTES:20} module-cleanup: enabled: ${AIIMAGE_MODULE_CLEANUP_ENABLED:true} cron: ${AIIMAGE_MODULE_CLEANUP_CRON:0 0 0 * * *} diff --git a/backend-java/src/main/resources/db/V24__price_track_tables.sql b/backend-java/src/main/resources/db/V24__price_track_tables.sql new file mode 100644 index 0000000..f10c436 --- /dev/null +++ b/backend-java/src/main/resources/db/V24__price_track_tables.sql @@ -0,0 +1,14 @@ +CREATE TABLE IF NOT EXISTS biz_price_track_shop_candidate ( + id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT 'primary key', + user_id BIGINT NOT NULL COMMENT 'user id', + shop_name VARCHAR(255) NOT NULL COMMENT 'normalized shop name', + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'created time', + UNIQUE KEY uk_user_shop (user_id, shop_name), + KEY idx_user_id (user_id) +) COMMENT='price track candidate shops'; + +CREATE TABLE IF NOT EXISTS biz_price_track_country_pref ( + user_id BIGINT NOT NULL PRIMARY KEY COMMENT 'user id', + country_codes_json VARCHAR(256) NOT NULL COMMENT 'country code order json', + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'updated time' +) COMMENT='price track country preference'; diff --git a/backend-java/src/main/resources/db/V25__permission_menu_sort_order.sql b/backend-java/src/main/resources/db/V25__permission_menu_sort_order.sql new file mode 100644 index 0000000..74322ce --- /dev/null +++ b/backend-java/src/main/resources/db/V25__permission_menu_sort_order.sql @@ -0,0 +1,6 @@ +ALTER TABLE `columns` + ADD COLUMN `sort_order` INT NOT NULL DEFAULT 0 COMMENT '菜单排序' AFTER `route_path`; + +UPDATE `columns` +SET `sort_order` = `id` +WHERE `sort_order` = 0; diff --git a/backend-java/src/main/resources/db/V25__shop_manage_group_bind_user.sql b/backend-java/src/main/resources/db/V25__shop_manage_group_bind_user.sql new file mode 100644 index 0000000..af919d6 --- /dev/null +++ b/backend-java/src/main/resources/db/V25__shop_manage_group_bind_user.sql @@ -0,0 +1,55 @@ +SET @db_name = DATABASE(); + +SET @user_id_col_exists := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db_name + AND TABLE_NAME = 'biz_shop_manage_group' + AND COLUMN_NAME = 'user_id' +); + +SET @sql_add_user_id_col := IF(@user_id_col_exists = 0, + 'ALTER TABLE biz_shop_manage_group ADD COLUMN user_id BIGINT NULL COMMENT ''关联用户ID'' AFTER group_name', + 'SELECT 1' +); +PREPARE stmt_add_user_id_col FROM @sql_add_user_id_col; +EXECUTE stmt_add_user_id_col; +DEALLOCATE PREPARE stmt_add_user_id_col; + +UPDATE biz_shop_manage_group g +LEFT JOIN users u ON u.username = g.group_name +SET g.user_id = u.id +WHERE g.user_id IS NULL + AND u.id IS NOT NULL; + +SET @user_id_idx_exists := ( + SELECT COUNT(*) + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = @db_name + AND TABLE_NAME = 'biz_shop_manage_group' + AND INDEX_NAME = 'idx_user_id' +); + +SET @sql_add_user_id_idx := IF(@user_id_idx_exists = 0, + 'ALTER TABLE biz_shop_manage_group ADD INDEX idx_user_id (user_id)', + 'SELECT 1' +); +PREPARE stmt_add_user_id_idx FROM @sql_add_user_id_idx; +EXECUTE stmt_add_user_id_idx; +DEALLOCATE PREPARE stmt_add_user_id_idx; + +SET @user_id_uk_exists := ( + SELECT COUNT(*) + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = @db_name + AND TABLE_NAME = 'biz_shop_manage_group' + AND INDEX_NAME = 'uk_user_id' +); + +SET @sql_add_user_id_uk := IF(@user_id_uk_exists = 0, + 'ALTER TABLE biz_shop_manage_group ADD UNIQUE KEY uk_user_id (user_id)', + 'SELECT 1' +); +PREPARE stmt_add_user_id_uk FROM @sql_add_user_id_uk; +EXECUTE stmt_add_user_id_uk; +DEALLOCATE PREPARE stmt_add_user_id_uk; diff --git a/backend/__pycache__/config.cpython-312.pyc b/backend/__pycache__/config.cpython-312.pyc index 57fc226f5d7255b16ddbf4efe022298ae6eb1d8c..8a02d24c8df3cd8ab635c7c3caa642aafd4bd0b3 100644 GIT binary patch delta 20 acmaFH{fwLYG%qg~0}!;&d$^JNHY)%^ng)LW delta 20 acmaFH{fwLYG%qg~0}#BBy1SA4HY)%^6$V%U diff --git a/backend/blueprints/__pycache__/admin_api.cpython-312.pyc b/backend/blueprints/__pycache__/admin_api.cpython-312.pyc index 268c8ae2e9b88c92e6366e1ba14175d0e1c509ac..4b38d6bfa5382dc85954c23c0ea5130358131aae 100644 GIT binary patch literal 84968 zcmd?S33L?KnJC=*F7>8;qlF}pKuGNSVr{HKED{F9A`4XuB(&ga$$;E4auVAj#z6!p zh?vA8<0K+>Y&pprD~Xc;wqxSV{Hg9zel6?rH(a z%>3uPSD@Rss_wmY>(;&B{(bj%2?-Vz9Q4RPx6DdVtNsN~goE6Hle?2vmFk>|Qq`*{ zHKl1&*Q?2|rd~sSwe?!^tE<<+ueMF!Zm2i38|#hjrg~Gmx!$bi>RIY7a9`JEZMW6i z$TfXiLVIF;BFP)t?Cp+vN4vA$3FpQ`>UtMt`iiRFO_?E0f|{1LC?OEH> z+SBXP+cWAj)GCe2YoMIoX_V_N_nTVo1?oLi5|vD)P^lNRR2r2|WsqDZl|^NfT+Rh; zeXcjRwMuwl>6e;Dd8k}cYC4ri<&#_iHG`T-a)ne8HH+kCQ^nLAk}J8Oe^br10R1n8 zKIc&y{@>gSI%?imH1+w^e7IgfEr4_ewGh&o)FMa=sR3&7SJd@I)Dk$GMJJpt)_uc!5(^bSIfDiiwUbx`GBQN79E z5Ps_y#;I2!t5>N|Z&93jRn*#p>bKUtso@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SFKGf%p5a5~8gJO$`=I1@7DkDQ5==oXaR08rpxhsLhkP$1|vXK0dTJ+lGVMYMc7``B5bc|rBQwy8cuhnOBp(W z06zni15WTKF0st$s7&~ktN`q_tPy)HJ3$g`?=X!J%~JUZoV#5JM(rYb5EB`nX1nhT zHqPyU_`lgXaD#@Kcu!&rOmF-WyBrPAOeK9D(AW2&Obf0r79L4ohj$h!J@ZHnZXN|T z&zY>U>tg1nCaJrnsY(5W!O$I&C*!c|lu30YmprdrTSpoS(eD^DH+Qx-!F32Z3lSXH zx2+h;Mi5k<#;r4j^Wkv!PpZ z^>nt@%FjX`{O3Y*%}T=pqC_v07)cxN`a?W7;M((!Ufy`4RaGE&J8*U(E&PARxxDaH;jTn!^2VM!hj9oRm#`ou* zA`=+)3?1^sxDlf9=$#~iJnSymef{pmh+WOFt997Z;zo$ZyY$F6?p}(>(;0G(4tYl0 z2+?@GhCC2BMY0)Itqv;~H$t>LUZ3o363tF}Npe(xhw*rh609c~(Q%|Rl{YzV#CUv0 zatuYgdv>>Bw`y2}nPgQ8dwSf6@pz36d(-X?#Gc8p&3f!vaU;g#z9e=z%%k#$da~N* z*Nr15ZiHyOQdz#3WVGh#aw_6Rh{l&D=OOzP$zcs;5p!~Uxp5;z<8uee}kM1tA2T4JHRMleFDn0(5|we pfmCGV=*q4l=Yb5(m*ShtlzSVfJ+^Ot3`^t&@n-d7Y{{i`;T(tlI diff --git a/backend/blueprints/admin_api.py b/backend/blueprints/admin_api.py index c225db2..c5a0e46 100644 --- a/backend/blueprints/admin_api.py +++ b/backend/blueprints/admin_api.py @@ -62,6 +62,34 @@ ADMIN_MENU_ACCESS_CONFIG = { }, } +ADMIN_MENU_ACCESS_CONFIG.update({ + 'users': { + 'column_key': 'admin_users', + 'route_path': 'users', + 'error': '无权访问用户管理模块', + }, + 'columns': { + 'column_key': 'admin_columns', + 'route_path': 'columns', + 'error': '无权访问栏目权限配置模块', + }, + 'shop-keys': { + 'column_key': 'admin_shop_keys', + 'route_path': 'shop-keys', + 'error': '无权访问店铺密钥管理模块', + }, + 'history': { + 'column_key': 'admin_history', + 'route_path': 'history', + 'error': '无权访问查看生成记录模块', + }, + 'version': { + 'column_key': 'admin_version', + 'route_path': 'version', + 'error': '无权访问版本管理模块', + }, +}) + def _safe_version_key(version): """将版本号转换为安全的 OSS 对象名片段""" @@ -98,10 +126,155 @@ def _format_permission_item(item): 'column_key': item.get('columnKey') or '', 'menu_type': item.get('menuType') or 'app', 'route_path': item.get('routePath') or '', + 'sort_order': item.get('sortOrder') if item.get('sortOrder') is not None else 0, 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16], } +def _parse_optional_int(value): + if value is None: + return None + text = str(value).strip() + if text == '': + return None + return int(text) + + +def _ensure_column_sort_schema(): + conn = get_db() + try: + with conn.cursor() as cur: + try: + cur.execute("ALTER TABLE columns ADD COLUMN sort_order INT NOT NULL DEFAULT 0 COMMENT '菜单排序' AFTER route_path") + except Exception: + pass + try: + cur.execute("UPDATE columns SET sort_order = id WHERE sort_order IS NULL OR sort_order = 0") + except Exception: + pass + conn.commit() + finally: + conn.close() + + +def _load_local_column_sort_map(): + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + cur.execute("SELECT id, sort_order FROM columns") + rows = cur.fetchall() + return {int(row['id']): int(row.get('sort_order') or 0) for row in rows if row.get('id') is not None} + finally: + conn.close() + + +def _load_local_columns(menu_type=None): + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + sql = """ + SELECT id, name, column_key, menu_type, route_path, sort_order, created_at + FROM columns + """ + params = [] + if menu_type: + sql += " WHERE menu_type = %s" + params.append(menu_type) + sql += " ORDER BY sort_order ASC, id ASC" + cur.execute(sql, params) + return cur.fetchall() + finally: + conn.close() + + +def _sync_local_columns_from_backend(items): + if not items: + return + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + for item in items: + item_id = item.get('id') + if item_id is None: + continue + sort_order = item.get('sort_order') + cur.execute( + """ + INSERT INTO columns (id, name, column_key, menu_type, route_path, sort_order, created_at) + VALUES (%s, %s, %s, %s, %s, %s, COALESCE(%s, NOW())) + ON DUPLICATE KEY UPDATE + name = VALUES(name), + column_key = VALUES(column_key), + menu_type = VALUES(menu_type), + route_path = VALUES(route_path), + sort_order = CASE + WHEN columns.sort_order IS NULL OR columns.sort_order = 0 THEN VALUES(sort_order) + ELSE columns.sort_order + END + """, + ( + int(item_id), + item.get('name') or '', + item.get('column_key') or '', + item.get('menu_type') or 'app', + item.get('route_path') or '', + int(sort_order if sort_order not in (None, '') else item_id), + item.get('created_at') or None, + ), + ) + conn.commit() + finally: + conn.close() + + +def _set_local_column_sort_order(column_id, sort_order): + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + cur.execute( + "UPDATE columns SET sort_order = %s WHERE id = %s", + (int(sort_order), int(column_id)), + ) + conn.commit() + finally: + conn.close() + + +def _get_next_local_column_sort_order(): + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + cur.execute("SELECT COALESCE(MAX(sort_order), 0) AS max_sort FROM columns") + row = cur.fetchone() or {} + return int(row.get('max_sort') or 0) + 1 + finally: + conn.close() + + +def _swap_local_column_sort_order(column_id, target_id): + _ensure_column_sort_schema() + conn = get_db() + try: + with conn.cursor() as cur: + cur.execute("SELECT id, sort_order FROM columns WHERE id IN (%s, %s) ORDER BY id", (int(column_id), int(target_id))) + rows = cur.fetchall() + if len(rows) != 2: + raise ValueError('菜单不存在') + by_id = {int(row['id']): int(row.get('sort_order') or 0) for row in rows} + left_sort = by_id.get(int(column_id), 0) or int(column_id) + right_sort = by_id.get(int(target_id), 0) or int(target_id) + cur.execute("UPDATE columns SET sort_order = %s WHERE id = %s", (right_sort, int(column_id))) + cur.execute("UPDATE columns SET sort_order = %s WHERE id = %s", (left_sort, int(target_id))) + conn.commit() + finally: + conn.close() + + def _sync_user_column_permissions(user_id, column_ids): _, error_response, status = _proxy_backend_java( 'PUT', @@ -111,8 +284,14 @@ def _sync_user_column_permissions(user_id, column_ids): return error_response, status +def _get_current_admin_id(current_row=None): + if current_row and current_row.get('id'): + return current_row.get('id') + return session.get('user_id') + + def _get_current_admin_permission_sets(): - user_id = session.get('user_id') + user_id = _get_current_admin_id() if not user_id: return set(), set() conn = get_db() @@ -152,6 +331,60 @@ def _ensure_admin_menu_access(*menu_names): return role, current_row, (jsonify({'success': False, 'error': error_message}), 403) +def _ensure_dedupe_total_data_access(): + return _ensure_admin_menu_access('dedupe-total-data') + + +def _load_current_admin_menu_items(): + role, current_row = get_current_admin_role() + if not role or not current_row: + return None, None, None, (jsonify({'success': False, 'error': '需要管理员权限'}), 403) + user_id = _get_current_admin_id(current_row) + if not user_id: + return role, current_row, None, (jsonify({'success': False, 'error': '当前登录用户缺少有效ID'}), 400) + result, error_response, status = _proxy_backend_java( + 'GET', + f'/api/admin/permission-users/{user_id}/column-permissions', + params={'menuType': 'admin'}, + ) + if error_response is not None: + return role, current_row, None, (error_response, status) + items = [_format_permission_item(item) for item in (result.get('data') or [])] + return role, current_row, items, None + + +@admin_api.route('/current-user') +@admin_required +def get_admin_current_user(): + role, current_row = get_current_admin_role() + if not role or not current_row: + return jsonify({'success': False, 'error': '需要管理员权限'}), 403 + return jsonify({ + 'success': True, + 'item': { + 'id': current_row.get('id'), + 'username': current_row.get('username') or session.get('username') or '', + 'role': role, + } + }) + + +@admin_api.route('/current-user/menus') +@admin_required +def get_admin_current_user_menus(): + _, _, items, denied = _load_current_admin_menu_items() + if denied: + return denied + return jsonify({'success': True, 'items': items}) + + +@admin_api.route('/logout', methods=['POST']) +@admin_required +def admin_logout(): + session.clear() + return jsonify({'success': True, 'msg': '退出成功', 'redirect': '/login'}) + + # ---------- 用户管理 ---------- @admin_api.route('/users') @@ -162,7 +395,13 @@ def list_users(): if not role: return jsonify({'success': False, 'error': '需要管理员权限'}), 403 page = max(1, int(request.args.get('page', 1))) - page_size = min(50, max(5, int(request.args.get('page_size', 15)))) + _, _, denied = _ensure_admin_menu_access('users', 'history', 'shop-manage', 'skip-price-asin') + if denied: + return denied + _, _, denied = _ensure_admin_menu_access('users', 'history', 'shop-manage', 'skip-price-asin') + if denied: + return denied + page_size = min(999, max(5, int(request.args.get('page_size', 15)))) offset = (page - 1) * page_size search_username = (request.args.get('username') or request.args.get('search') or '').strip() created_by_id_arg = request.args.get('created_by_id') or request.args.get('admin_id') @@ -249,6 +488,9 @@ def list_users(): @admin_api.route('/user', methods=['POST']) @admin_required def create_user(): + _, _, denied = _ensure_admin_menu_access('users') + if denied: + return denied data = request.get_json() or {} username = (data.get('username') or '').strip() password = data.get('password') or '' @@ -312,6 +554,9 @@ def create_user(): def update_user(uid): """更新用户(密码、角色)""" data = request.get_json() or {} + _, _, denied = _ensure_admin_menu_access('users') + if denied: + return denied password = data.get('password') want_role = (data.get('role') or '').strip() or data.get('role') role, current_row = get_current_admin_role() @@ -368,6 +613,9 @@ def update_user(uid): @admin_required def delete_user(uid): """删除用户""" + _, _, denied = _ensure_admin_menu_access('users') + if denied: + return denied if session.get('user_id') == uid: return jsonify({'success': False, 'error': '不能删除当前登录账号'}) role, current_row = get_current_admin_role() @@ -405,6 +653,9 @@ def delete_user(uid): @admin_required def history(): """管理员分页获取所有生成记录""" + _, _, denied = _ensure_admin_menu_access('history') + if denied: + return denied page = max(1, int(request.args.get('page', 1))) page_size = min(50, max(10, int(request.args.get('page_size', 15)))) offset = (page - 1) * page_size @@ -473,28 +724,49 @@ def history(): @admin_api.route('/columns') @admin_required def list_columns(): - params = {} + _, _, denied = _ensure_admin_menu_access('columns', 'users') + if denied: + return denied menu_type = (request.args.get('menu_type') or '').strip() - if menu_type: - params['menuType'] = menu_type + params = {'menuType': menu_type} if menu_type else None result, error_response, status = _proxy_backend_java( 'GET', '/api/admin/permission-menus', - params=params or None, + params=params, ) - if error_response is not None: - return error_response, status - return jsonify({'success': True, 'items': [_format_permission_item(item) for item in (result.get('data') or [])]}) + if error_response is None: + _sync_local_columns_from_backend([_format_permission_item(item) for item in (result.get('data') or [])]) + local_rows = _load_local_columns(menu_type or None) + items = [ + { + 'id': row.get('id'), + 'name': row.get('name') or '', + 'column_key': row.get('column_key') or '', + 'menu_type': row.get('menu_type') or 'app', + 'route_path': row.get('route_path') or '', + 'sort_order': int(row.get('sort_order') or 0), + 'created_at': str(row.get('created_at') or '')[:16].replace('T', ' '), + } + for row in local_rows + ] + return jsonify({'success': True, 'items': items}) @admin_api.route('/column', methods=['POST']) @admin_required def create_column(): + _, _, denied = _ensure_admin_menu_access('columns') + if denied: + return denied data = request.get_json() or {} name = (data.get('name') or '').strip() column_key = (data.get('column_key') or '').strip() - menu_type = (data.get('menu_type') or 'app').strip() or 'app' + menu_type = (data.get('menu_type') or '').strip() or 'admin' route_path = (data.get('route_path') or '').strip() + try: + sort_order = _parse_optional_int(data.get('sort_order')) + except (TypeError, ValueError): + return jsonify({'success': False, 'error': '排序必须是数字'}) if not name: return jsonify({'success': False, 'error': '栏目名不能为空'}) if not column_key: @@ -514,17 +786,27 @@ def create_column(): if error_response is not None: return error_response, status item = result.get('data') or {} + _sync_local_columns_from_backend([_format_permission_item(item)]) + if item.get('id') is not None: + _set_local_column_sort_order(item.get('id'), sort_order if sort_order is not None else _get_next_local_column_sort_order()) return jsonify({'success': True, 'msg': result.get('message') or '创建成功', 'id': item.get('id')}) @admin_api.route('/column/', methods=['PUT']) @admin_required def update_column(cid): + _, _, denied = _ensure_admin_menu_access('columns') + if denied: + return denied data = request.get_json() or {} name = (data.get('name') or '').strip() column_key = (data.get('column_key') or '').strip() - menu_type = (data.get('menu_type') or 'app').strip() or 'app' + menu_type = (data.get('menu_type') or '').strip() or 'admin' route_path = (data.get('route_path') or '').strip() + try: + sort_order = _parse_optional_int(data.get('sort_order')) + except (TypeError, ValueError): + return jsonify({'success': False, 'error': '排序必须是数字'}) if not name: return jsonify({'success': False, 'error': '栏目名不能为空'}) if not column_key: @@ -543,32 +825,76 @@ def update_column(cid): ) if error_response is not None: return error_response, status + _sync_local_columns_from_backend([{ + 'id': cid, + 'name': name, + 'column_key': column_key, + 'menu_type': menu_type, + 'route_path': route_path, + 'sort_order': sort_order if sort_order is not None else cid, + 'created_at': None, + }]) + if sort_order is not None: + _set_local_column_sort_order(cid, sort_order) return jsonify({'success': True, 'msg': result.get('message') or '更新成功'}) +@admin_api.route('/column/reorder', methods=['POST']) +@admin_required +def reorder_column(): + _, _, denied = _ensure_admin_menu_access('columns') + if denied: + return denied + data = request.get_json() or {} + try: + column_id = int(data.get('column_id')) + target_id = int(data.get('target_id')) + except (TypeError, ValueError): + return jsonify({'success': False, 'error': '菜单重排参数无效'}), 400 + if column_id == target_id: + return jsonify({'success': True, 'msg': '排序未变化'}) + try: + _swap_local_column_sort_order(column_id, target_id) + except ValueError as exc: + return jsonify({'success': False, 'error': str(exc)}), 400 + except Exception as exc: + return jsonify({'success': False, 'error': str(exc)}), 500 + return jsonify({'success': True, 'msg': '排序更新成功'}) + + @admin_api.route('/column/', methods=['DELETE']) @admin_required def delete_column(cid): + _, _, denied = _ensure_admin_menu_access('columns') + if denied: + return denied result, error_response, status = _proxy_backend_java( 'DELETE', f'/api/admin/permission-menus/{cid}', ) if error_response is not None: return error_response, status + conn = get_db() + try: + with conn.cursor() as cur: + cur.execute("DELETE FROM columns WHERE id = %s", (cid,)) + conn.commit() + finally: + conn.close() return jsonify({'success': True, 'msg': result.get('message') or '删除成功'}) @admin_api.route('/user//columns') @admin_required def get_user_columns(uid): - params = {} + _, _, denied = _ensure_admin_menu_access('users') + if denied: + return denied menu_type = (request.args.get('menu_type') or '').strip() - if menu_type: - params['menuType'] = menu_type result, error_response, status = _proxy_backend_java( 'GET', f'/api/admin/permission-users/{uid}/columns', - params=params or None, + params={'menuType': menu_type} if menu_type else None, ) if error_response is not None: return error_response, status @@ -579,14 +905,14 @@ def get_user_columns(uid): @admin_api.route('/user//column-permissions') @admin_required def get_user_column_permissions(uid): - params = {} + _, _, denied = _ensure_admin_menu_access('users') + if denied: + return denied menu_type = (request.args.get('menu_type') or '').strip() - if menu_type: - params['menuType'] = menu_type result, error_response, status = _proxy_backend_java( 'GET', f'/api/admin/permission-users/{uid}/column-permissions', - params=params or None, + params={'menuType': menu_type} if menu_type else None, ) if error_response is not None: return error_response, status @@ -610,6 +936,9 @@ def _set_user_column_permissions(cur, user_id, column_ids): @admin_api.route('/versions') @admin_required def list_versions(): + _, _, denied = _ensure_admin_menu_access('version') + if denied: + return denied """获取版本列表""" try: conn = get_db() @@ -637,6 +966,9 @@ def list_versions(): @admin_required def upload_version(): """接收版本号 + zip 文件,上传到 OSS,写入 web_config""" + _, _, denied = _ensure_admin_menu_access('version') + if denied: + return denied version = (request.form.get('version') or '').strip() if not version: return jsonify({'success': False, 'error': '请填写版本号'}) @@ -675,6 +1007,9 @@ def upload_version(): @admin_api.route('/shop-keys') @admin_required def list_shop_keys(): + _, _, denied = _ensure_admin_menu_access('shop-keys') + if denied: + return denied page = max(1, int(request.args.get('page', 1))) page_size = min(100, max(1, int(request.args.get('page_size', 15)))) result, error_response, status = _proxy_backend_java( @@ -707,6 +1042,9 @@ def list_shop_keys(): @admin_api.route('/shop-key', methods=['POST']) @admin_required def create_shop_key(): + _, _, denied = _ensure_admin_menu_access('shop-keys') + if denied: + return denied data = request.get_json() or {} payload = { 'ziniaoAccountName': (data.get('ziniao_account_name') or '').strip(), @@ -736,6 +1074,9 @@ def create_shop_key(): @admin_api.route('/shop-key/', methods=['PUT']) @admin_required def update_shop_key(item_id): + _, _, denied = _ensure_admin_menu_access('shop-keys') + if denied: + return denied data = request.get_json() or {} payload = { 'ziniaoAccountName': (data.get('ziniao_account_name') or '').strip(), @@ -765,6 +1106,9 @@ def update_shop_key(item_id): @admin_api.route('/shop-key/', methods=['DELETE']) @admin_required def delete_shop_key(item_id): + _, _, denied = _ensure_admin_menu_access('shop-keys') + if denied: + return denied result, error_response, status = _proxy_backend_java( 'DELETE', f'/api/admin/shop-keys/{item_id}', @@ -1007,8 +1351,9 @@ def list_shop_manages(): shop_name = (request.args.get('shop_name') or '').strip() params = {'page': page, 'pageSize': page_size} - if role != 'super_admin' and current_row and current_row.get('id'): - params['createdById'] = current_row.get('id') + if current_row and current_row.get('id'): + params['operatorId'] = current_row.get('id') + params['superAdmin'] = 'true' if role == 'super_admin' else 'false' if group_id_raw: try: group_id = int(group_id_raw) @@ -1164,10 +1509,16 @@ def list_shop_manage_groups(): role, current_row, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') if denied: return denied + params = {} + if current_row and current_row.get('id'): + params['operatorId'] = current_row.get('id') + params['superAdmin'] = 'true' if role == 'super_admin' else 'false' + if role != 'super_admin' and current_row and current_row.get('id'): + params['createdById'] = current_row.get('id') result, error_response, status = _proxy_backend_java( 'GET', '/api/admin/shop-manages/groups', - params={'createdById': current_row.get('id')} if role != 'super_admin' and current_row and current_row.get('id') else None, + params=params, ) if error_response is not None: return error_response, status @@ -1175,6 +1526,8 @@ def list_shop_manage_groups(): { 'id': item.get('id'), 'group_name': item.get('groupName') or '', + 'user_id': item.get('userId'), + 'username': item.get('username') or '', 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16], 'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16], } @@ -1186,17 +1539,22 @@ def list_shop_manage_groups(): @admin_api.route('/shop-manage-group', methods=['POST']) @admin_required def create_shop_manage_group(): - _, current_row, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') + role, current_row, denied = _ensure_admin_menu_access('shop-manage', 'skip-price-asin') if denied: return denied data = request.get_json() or {} payload = { 'groupName': (data.get('group_name') or '').strip(), + 'userId': data.get('user_id'), 'createdById': current_row.get('id') if current_row else None, } result, error_response, status = _proxy_backend_java( 'POST', '/api/admin/shop-manages/groups', + params={ + 'operatorId': current_row.get('id') if current_row else None, + 'superAdmin': 'true' if role == 'super_admin' else 'false', + }, json_data=payload, ) if error_response is not None: @@ -1208,6 +1566,8 @@ def create_shop_manage_group(): 'item': { 'id': item.get('id'), 'group_name': item.get('groupName') or '', + 'user_id': item.get('userId'), + 'username': item.get('username') or '', 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16], 'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16], }, @@ -1221,7 +1581,10 @@ def update_shop_manage_group(item_id): if denied: return denied data = request.get_json() or {} - payload = {'groupName': (data.get('group_name') or '').strip()} + payload = { + 'groupName': (data.get('group_name') or '').strip(), + 'userId': data.get('user_id'), + } result, error_response, status = _proxy_backend_java( 'PUT', f'/api/admin/shop-manages/groups/{item_id}', @@ -1240,6 +1603,8 @@ def update_shop_manage_group(item_id): 'item': { 'id': item.get('id'), 'group_name': item.get('groupName') or '', + 'user_id': item.get('userId'), + 'username': item.get('username') or '', 'created_at': (item.get('createdAt') or '').replace('T', ' ')[:16], 'updated_at': (item.get('updatedAt') or '').replace('T', ' ')[:16], }, @@ -1249,7 +1614,7 @@ def update_shop_manage_group(item_id): @admin_api.route('/skip-price-asins') @admin_required def list_skip_price_asins(): - _, _, denied = _ensure_admin_menu_access('skip-price-asin') + role, current_row, denied = _ensure_admin_menu_access('skip-price-asin') if denied: return denied page = max(1, int(request.args.get('page', 1))) @@ -1258,6 +1623,9 @@ def list_skip_price_asins(): shop_name = (request.args.get('shop_name') or '').strip() asin = (request.args.get('asin') or '').strip() params = {'page': page, 'pageSize': page_size} + if current_row and current_row.get('id'): + params['operatorId'] = current_row.get('id') + params['superAdmin'] = 'true' if role == 'super_admin' else 'false' if group_id_raw: try: group_id = int(group_id_raw) @@ -1305,19 +1673,31 @@ def list_skip_price_asins(): @admin_api.route('/skip-price-asin', methods=['POST']) @admin_required def create_skip_price_asin(): - _, _, denied = _ensure_admin_menu_access('skip-price-asin') + role, current_row, denied = _ensure_admin_menu_access('skip-price-asin') if denied: return denied data = request.get_json() or {} + asin_mappings = data.get('asin_mappings') or {} + fallback_asin = (data.get('asin') or '').strip() + if not fallback_asin and isinstance(asin_mappings, dict): + for value in asin_mappings.values(): + fallback_asin = (value or '').strip() + if fallback_asin: + break payload = { 'groupId': data.get('group_id'), 'shopName': (data.get('shop_name') or '').strip(), 'countries': data.get('countries') or [], - 'asin': (data.get('asin') or '').strip(), + 'asin': fallback_asin, + 'asinMappings': asin_mappings, } result, error_response, status = _proxy_backend_java( 'POST', '/api/admin/skip-price-asins', + params={ + 'operatorId': current_row.get('id') if current_row else None, + 'superAdmin': 'true' if role == 'super_admin' else 'false', + }, json_data=payload, ) if error_response is not None: @@ -1345,12 +1725,16 @@ def create_skip_price_asin(): @admin_api.route('/skip-price-asin//country/', methods=['DELETE']) @admin_required def delete_skip_price_asin_country(item_id, country): - _, _, denied = _ensure_admin_menu_access('skip-price-asin') + role, current_row, denied = _ensure_admin_menu_access('skip-price-asin') if denied: return denied result, error_response, status = _proxy_backend_java( 'DELETE', f'/api/admin/skip-price-asins/{item_id}/countries/{country}', + params={ + 'operatorId': current_row.get('id') if current_row else None, + 'superAdmin': 'true' if role == 'super_admin' else 'false', + }, ) if error_response is not None: return error_response, status @@ -1379,7 +1763,7 @@ def delete_shop_manage_group(item_id): @admin_api.route('/skip-price-asin//country/', methods=['PUT']) @admin_required def update_skip_price_asin_country(item_id, country): - _, _, denied = _ensure_admin_menu_access('skip-price-asin') + role, current_row, denied = _ensure_admin_menu_access('skip-price-asin') if denied: return denied data = request.get_json() or {} @@ -1387,6 +1771,10 @@ def update_skip_price_asin_country(item_id, country): result, error_response, status = _proxy_backend_java( 'PUT', f'/api/admin/skip-price-asins/{item_id}/countries/{country}', + params={ + 'operatorId': current_row.get('id') if current_row else None, + 'superAdmin': 'true' if role == 'super_admin' else 'false', + }, json_data=payload, ) if error_response is not None: diff --git a/backend/utils/__pycache__/db.cpython-312.pyc b/backend/utils/__pycache__/db.cpython-312.pyc index 74e09849dc3c7efc744df9d3918552722660420a..7b0e8ace4856a93b43747b263bab1ed37729d453 100644 GIT binary patch delta 919 zcmYk3O-vI(6oBWaYr8EiUCYu!TUekC^+14F0tXN(6nB@OBD5+-ZIEI>DwwteH6TWf z!30E^cp=7cQ^N()gNgBA_=(*mnix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' + (item.name || item.route_path) + ''; + }).join(''); + } + document.querySelectorAll('#adminTabs .tab').forEach(function (tab) { + tab.onclick = function () { + activateAdminTab(tab.dataset.tab); + }; + }); + var fallbackTab = activeAdminTabName && knownItems.some(function (item) { return item.route_path === activeAdminTabName; }) + ? activeAdminTabName + : knownItems[0].route_path; + activateAdminTab(fallbackTab); + } + function loadAdminMenus(preferredTab) { + if (preferredTab) activeAdminTabName = preferredTab; + fetch('/api/admin/current-user/menus') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + if (adminTabsEl) adminTabsEl.innerHTML = '

菜单加载失败
'; + hideAllAdminPanels(); + return; + } + renderAdminTabs(res.items || []); + }) + .catch(function () { + if (adminTabsEl) adminTabsEl.innerHTML = '
菜单加载失败
'; + hideAllAdminPanels(); + }); + } + hideAllAdminPanels(); + + // ========== 用户管理 ========== + var userPage = 1, userPageSize = 15; + var currentUserId = null; + var currentUserRole = 'admin'; + var currentUserUsername = ''; + var adminsList = []; + function roleLabel(role) { + if (role === 'super_admin') return '超级管理员'; + if (role === 'admin') return '管理员'; + return '普通账号'; + } + function buildUserListQuery(page) { + var q = 'page=' + (page || 1) + '&page_size=' + userPageSize; + var kw = (document.getElementById('searchUsername').value || '').trim(); + if (kw) q += '&username=' + encodeURIComponent(kw); + var cby = document.getElementById('filterCreatedBy').value; + if (cby) q += '&created_by_id=' + encodeURIComponent(cby); + return q; + } + function loadUsers(page) { + userPage = page || 1; + fetch('/api/admin/users?' + buildUserListQuery(userPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('userListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + currentUserId = res.current_user_id || null; + currentUserRole = res.current_user_role || 'admin'; + currentUserUsername = (res.current_user_username || '').trim(); + adminsList = res.admins || []; + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无用户'; + } else { + tbody.innerHTML = items.map(function (u) { + return '' + u.id + '' + (u.username || '') + '' + + roleLabel(u.role || 'normal') + '' + (u.creator_username || '-') + '' + (u.created_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('userPagination', res.total, res.page, res.page_size, loadUsers); + bindUserActions(); + updateCreateFormByRole(); + updateUserFilterByRole(); + }) + .catch(function () { + document.getElementById('userListBody').innerHTML = '请求失败'; + }); + } + function updateUserFilterByRole() { + var grp = document.getElementById('filterCreatedByGroup'); + var sel = document.getElementById('filterCreatedBy'); + if (currentUserRole === 'super_admin') { + grp.style.display = 'block'; + var cur = sel.value; + sel.innerHTML = ''; + adminsList.forEach(function (a) { + var opt = document.createElement('option'); + opt.value = a.id; + opt.textContent = a.username; + sel.appendChild(opt); + }); + sel.value = cur || ''; + } else { + grp.style.display = 'none'; + } + } + + function updateDedupeTotalDataAccess() { + var tab = document.querySelector('.tab[data-tab="dedupe-total-data"]'); + var panel = document.getElementById('panel-dedupe-total-data'); + var canUse = currentUserRole === 'super_admin' || (currentUserRole === 'admin' && currentUserUsername === ''); + if (tab) tab.style.display = canUse ? '' : 'none'; + if (panel) panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab && tab.classList.contains('active')) { + tab.classList.remove('active'); + if (panel) panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function updateShopManageAccess() { + var tab = document.querySelector('.tab[data-tab="shop-manage"]'); + var panel = document.getElementById('panel-shop-manage'); + if (!tab || !panel) return; + var canUse = currentUserRole === 'super_admin' || + !!currentUserAdminPermissionKeys['admin_shop_manage'] || + !!currentUserAdminPermissionRoutes['shop-manage']; + tab.style.display = canUse ? '' : 'none'; + panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab.classList.contains('active')) { + tab.classList.remove('active'); + panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function loadCurrentUserAdminPermissions() { + currentUserAdminPermissionKeys = {}; + currentUserAdminPermissionRoutes = {}; + if (!currentUserId || currentUserRole === 'super_admin') { + updateShopManageAccess(); + return; + } + fetch('/api/admin/user/' + currentUserId + '/column-permissions?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + updateShopManageAccess(); + return; + } + (res.items || []).forEach(function (item) { + var columnKey = (item.column_key || '').trim(); + var routePath = (item.route_path || '').trim(); + if (columnKey) currentUserAdminPermissionKeys[columnKey] = true; + if (routePath) currentUserAdminPermissionRoutes[routePath] = true; + }); + updateShopManageAccess(); + }) + .catch(function () { + updateShopManageAccess(); + }); + } + function applyTabAccess(tabName, canUse) { + var tab = document.querySelector('.tab[data-tab="' + tabName + '"]'); + var panel = document.getElementById('panel-' + tabName); + if (tab) tab.style.display = canUse ? '' : 'none'; + if (panel) panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab && tab.classList.contains('active')) { + tab.classList.remove('active'); + if (panel) panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function hasAdminTabAccess(tabName) { + var config = ADMIN_TAB_ACCESS_CONFIG[tabName]; + if (!config) return true; + if (currentUserRole === 'super_admin') return true; + if (config.superAdminOnly) return false; + return !!currentUserAdminPermissionKeys[config.columnKey] || + !!currentUserAdminPermissionRoutes[config.routePath]; + } + function refreshAdminTabAccess() { + Object.keys(ADMIN_TAB_ACCESS_CONFIG).forEach(function (tabName) { + applyTabAccess(tabName, hasAdminTabAccess(tabName)); + }); + } + function loadCurrentUserAdminPermissions() { + currentUserAdminPermissionKeys = {}; + currentUserAdminPermissionRoutes = {}; + if (!currentUserId || currentUserRole === 'super_admin') { + refreshAdminTabAccess(); + return; + } + fetch('/api/admin/user/' + currentUserId + '/column-permissions?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + refreshAdminTabAccess(); + return; + } + (res.items || []).forEach(function (item) { + var columnKey = (item.column_key || '').trim(); + var routePath = (item.route_path || '').trim(); + if (columnKey) currentUserAdminPermissionKeys[columnKey] = true; + if (routePath) currentUserAdminPermissionRoutes[routePath] = true; + }); + refreshAdminTabAccess(); + }) + .catch(function () { + refreshAdminTabAccess(); + }); + } + var allColumnsList = []; + function loadColumnsForPermission() { + fetch('/api/admin/columns?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) return; + allColumnsList = res.items || []; + renderColumnPermissionWrap('createColumnPermissionWrap'); + renderColumnPermissionWrap('editColumnPermissionWrap'); + var selCreate = document.getElementById('createColumnPermissionWrap'); + var selEdit = document.getElementById('editColumnPermissionWrap'); + if (selCreate && !selCreate._colCardsBound) { + selCreate._colCardsBound = true; + selCreate.onchange = function () { renderColumnCards('createColumnPermissionWrap'); }; + } + if (selEdit && !selEdit._colCardsBound) { + selEdit._colCardsBound = true; + selEdit.onchange = function () { renderColumnCards('editColumnPermissionWrap'); }; + } + }) + .catch(function () { }); + } + var columnCardsContainerMap = { createColumnPermissionWrap: 'createColumnCards', editColumnPermissionWrap: 'editColumnCards' }; + function renderColumnCards(selectId) { + var sel = document.getElementById(selectId); + var cardsId = columnCardsContainerMap[selectId]; + var cardsEl = cardsId ? document.getElementById(cardsId) : null; + if (!sel || sel.tagName !== 'SELECT' || !cardsEl) return; + cardsEl.innerHTML = ''; + for (var i = 0; i < sel.options.length; i++) { + var opt = sel.options[i]; + if (opt.disabled || !opt.selected) continue; + var card = document.createElement('span'); + card.className = 'column-permission-card'; + card.textContent = opt.textContent; + var btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'col-card-remove'; + btn.setAttribute('aria-label', '移除'); + btn.textContent = '×'; + (function (option, seldId) { + btn.onclick = function () { + option.selected = false; + renderColumnCards(seldId); + }; + })(opt, selectId); + card.appendChild(btn); + cardsEl.appendChild(card); + } + } + function renderColumnPermissionWrap(wrapId) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return; + sel.innerHTML = ''; + allColumnsList.forEach(function (c) { + var opt = document.createElement('option'); + opt.value = c.id; + opt.textContent = c.name + ' (' + c.column_key + ')'; + sel.appendChild(opt); + }); + if (allColumnsList.length === 0) { + var opt = document.createElement('option'); + opt.disabled = true; + opt.textContent = '暂无菜单,请先在“栏目权限配置”中新增菜单'; + sel.appendChild(opt); + } + renderColumnCards(wrapId); + } + function getSelectedColumnIds(wrapId) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return []; + var ids = []; + for (var i = 0; i < sel.options.length; i++) { + if (sel.options[i].selected) { + var v = parseInt(sel.options[i].value, 10); + if (!isNaN(v)) ids.push(v); + } + } + return ids; + } + function setColumnPermissionCheckboxes(wrapId, columnIds) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return; + var set = {}; + (columnIds || []).forEach(function (id) { set[id] = true; }); + for (var i = 0; i < sel.options.length; i++) { + var opt = sel.options[i]; + if (opt.disabled) continue; + opt.selected = set[parseInt(opt.value, 10)] || false; + } + renderColumnCards(wrapId); + } + function updateCreateFormByRole() { + var roleSel = document.getElementById('createRole'); + var optAdmin = document.getElementById('optAdmin'); + var formCreatedBy = document.getElementById('formGroupCreatedBy'); + var selCreatedBy = document.getElementById('createCreatedBy'); + if (currentUserRole === 'super_admin') { + if (optAdmin) optAdmin.style.display = ''; + formCreatedBy.style.display = (roleSel.value === 'normal') ? 'block' : 'none'; + selCreatedBy.innerHTML = ''; + adminsList.forEach(function (a) { + var opt = document.createElement('option'); + opt.value = a.id; + opt.textContent = a.username; + selCreatedBy.appendChild(opt); + }); + } else { + if (optAdmin) optAdmin.style.display = 'none'; + roleSel.value = 'normal'; + formCreatedBy.style.display = 'none'; + } + } + function bindUserActions() { + document.querySelectorAll('[data-edit]').forEach(function (btn) { + btn.onclick = function () { + var raw = (btn.getAttribute('data-user') || '{}').replace(/"/g, '"'); + var u; + try { u = JSON.parse(raw); } catch (e) { u = {}; } + document.getElementById('editUserId').value = u.id || ''; + document.getElementById('editUsername').value = u.username || ''; + document.getElementById('editPassword').value = ''; + var editRole = document.getElementById('editRole'); + var editFormGroupRole = document.getElementById('editFormGroupRole'); + var editFormGroupCreator = document.getElementById('editFormGroupCreator'); + var editCreatorName = document.getElementById('editCreatorName'); + editFormGroupRole.style.display = (currentUserRole === 'super_admin' && u.role !== 'super_admin') ? 'block' : 'none'; + editFormGroupCreator.style.display = (u.role === 'normal' && u.creator_username) ? 'block' : 'none'; + editCreatorName.value = u.creator_username || ''; + if (u.role !== 'super_admin') { editRole.value = u.role || 'normal'; } + document.getElementById('msgEdit').textContent = ''; + if (allColumnsList.length) { + renderColumnPermissionWrap('editColumnPermissionWrap'); + fetch('/api/admin/user/' + (u.id) + '/columns') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success && res.column_ids) setColumnPermissionCheckboxes('editColumnPermissionWrap', res.column_ids); + }); + } + document.getElementById('editUserModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-delete]').forEach(function (btn) { + btn.onclick = function () { + if (!confirm('确定删除用户 "' + (btn.dataset.name || '') + '" 吗?')) return; + fetch('/api/admin/user/' + btn.dataset.delete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadUsers(userPage); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + + document.getElementById('btnSearchUsers').onclick = function () { loadUsers(1); }; + document.getElementById('createRole').onchange = function () { updateCreateFormByRole(); }; + document.getElementById('btnCreate').onclick = function () { + var username = (document.getElementById('username').value || '').trim(); + var password = document.getElementById('password').value || ''; + var role = document.getElementById('createRole').value || 'normal'; + var createdById = document.getElementById('createCreatedBy').value ? parseInt(document.getElementById('createCreatedBy').value, 10) : null; + var msgEl = document.getElementById('msgCreate'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!username || username.length < 2) { + msgEl.textContent = '用户名至少 2 个字符'; + msgEl.classList.add('err'); + return; + } + if (!password || password.length < 6) { + msgEl.textContent = '密码至少 6 个字符'; + msgEl.classList.add('err'); + return; + } + var body = { username: username, password: password, role: role }; + if (role === 'normal' && currentUserRole === 'super_admin' && createdById) body.created_by_id = createdById; + body.column_ids = getSelectedColumnIds('createColumnPermissionWrap'); + fetch('/api/admin/user', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = res.msg || '创建成功'; + msgEl.classList.add('ok'); + document.getElementById('username').value = ''; + document.getElementById('password').value = ''; + loadUsers(1); + } else { + msgEl.textContent = res.error || '创建失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.classList.add('err'); + }); + }; + + document.getElementById('btnSaveUser').onclick = function () { + var uid = document.getElementById('editUserId').value; + var password = document.getElementById('editPassword').value; + var editRoleEl = document.getElementById('editRole'); + var msgEl = document.getElementById('msgEdit'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + var body = {}; + if (password) body.password = password; + if (currentUserRole === 'super_admin' && editRoleEl && editRoleEl.offsetParent !== null) + body.role = editRoleEl.value || 'normal'; + body.column_ids = getSelectedColumnIds('editColumnPermissionWrap'); + fetch('/api/admin/user/' + uid, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = res.msg || '保存成功'; + msgEl.classList.add('ok'); + document.getElementById('editUserModal').classList.remove('show'); + loadUsers(userPage); + if (String(uid || '') === String(currentUserId || '')) { + loadAdminMenus(getActiveAdminTabName()); + } + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }); + }; + document.getElementById('btnCloseEdit').onclick = function () { + document.getElementById('editUserModal').classList.remove('show'); + }; + + // ========== 生成记录 ========== + var historyPage = 1, historyPageSize = 15; + function toSqlDatetime(val) { + if (!val) return ''; + return val.replace('T', ' '); + } + function buildHistoryQuery(page) { + var q = 'page=' + (page || 1) + '&page_size=' + historyPageSize; + var uid = document.getElementById('filterUser').value; + var start = toSqlDatetime(document.getElementById('filterTimeStart').value); + var end = toSqlDatetime(document.getElementById('filterTimeEnd').value); + if (uid) q += '&user_id=' + uid; + if (start) q += '&time_start=' + encodeURIComponent(start); + if (end) q += '&time_end=' + encodeURIComponent(end); + return q; + } + function loadHistory(page) { + historyPage = page || 1; + fetch('/api/admin/history?' + buildHistoryQuery(historyPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('historyListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无记录'; + } else { + tbody.innerHTML = items.map(function (h) { + var urls = (h.result_urls || []); + var thumbUrls = (h.long_image_url ? [h.long_image_url] : []).concat(urls); + var thumbs = thumbUrls.slice(0, 3).map(function (url) { + return ''; + }).join(''); + return '' + h.id + '' + (h.username || '-') + '' + + (h.panel_type || '-') + '' + (h.created_at || '') + '' + + '
' + (thumbs || '-') + '
'; + }).join(''); + } + renderPagination('historyPagination', res.total, res.page, res.page_size, loadHistory); + }) + .catch(function () { + document.getElementById('historyListBody').innerHTML = '请求失败'; + }); + } + function loadUserOptions() { + fetch('/api/admin/users?page=1&page_size=999') + .then(function (r) { return r.json(); }) + .then(function (res) { + var sel = document.getElementById('filterUser'); + var cur = sel.value; + sel.innerHTML = ''; + (res.items || []).forEach(function (u) { + var opt = document.createElement('option'); + opt.value = u.id; + opt.textContent = u.username + ' (' + roleLabel(u.role || 'normal') + ')'; + sel.appendChild(opt); + }); + sel.value = cur || ''; + }); + } + var shopManageGroupUsers = []; + function refreshShopManageGroupUserSelect(selectedUserId) { + var sel = document.getElementById('shopManageGroupUserSelect'); + if (!sel) return; + var opts = ['']; + shopManageGroupUsers.forEach(function (u) { + opts.push(''); + }); + sel.innerHTML = opts.join(''); + if (selectedUserId != null && selectedUserId !== '') { + sel.value = String(selectedUserId); + } + syncShopManageGroupNameWithUser(); + } + function syncShopManageGroupNameWithUser() { + var sel = document.getElementById('shopManageGroupUserSelect'); + var input = document.getElementById('shopManageGroupInput'); + if (!sel || !input) return; + var selectedUser = null; + shopManageGroupUsers.some(function (u) { + if (String(u.id) === String(sel.value || '')) { + selectedUser = u; + return true; + } + return false; + }); + input.value = selectedUser ? (selectedUser.username || '') : ''; + } + function loadUserOptions() { + return fetch('/api/admin/users?page=1&page_size=999') + .then(function (r) { return r.json(); }) + .then(function (res) { + var items = res.items || []; + shopManageGroupUsers = items.map(function (u) { + return { id: u.id, username: u.username || '', role: u.role || 'normal' }; + }); + refreshShopManageGroupUserSelect(document.getElementById('shopManageGroupUserSelect') ? document.getElementById('shopManageGroupUserSelect').value : ''); + var sel = document.getElementById('filterUser'); + var cur = sel.value; + sel.innerHTML = ''; + items.forEach(function (u) { + var opt = document.createElement('option'); + opt.value = u.id; + opt.textContent = u.username + ' (' + roleLabel(u.role || 'normal') + ')'; + sel.appendChild(opt); + }); + sel.value = cur || ''; + }); + } + document.getElementById('btnFilterHistory').onclick = function () { loadHistory(1); }; + + // ========== 数据去重总数据 ========== + var dedupeTotalDataPage = 1, dedupeTotalDataPageSize = 15; + function buildDedupeTotalDataQuery(page) { + var q = 'page=' + (page || 1) + '&page_size=' + dedupeTotalDataPageSize; + var keyword = (document.getElementById('searchDedupeTotalData').value || '').trim(); + if (keyword) q += '&keyword=' + encodeURIComponent(keyword); + return q; + } + function loadDedupeTotalData(page) { + dedupeTotalDataPage = page || 1; + fetch('/api/admin/dedupe-total-data?' + buildDedupeTotalDataQuery(dedupeTotalDataPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('dedupeTotalDataListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无总数据'; + } else { + tbody.innerHTML = items.map(function (item) { + return '' + item.id + '' + (item.data_value || '') + '' + (item.created_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('dedupeTotalDataPagination', res.total, res.page, res.page_size, loadDedupeTotalData); + bindDedupeTotalDataActions(); + }) + .catch(function () { + document.getElementById('dedupeTotalDataListBody').innerHTML = '请求失败'; + }); + } + function bindDedupeTotalDataActions() { + document.querySelectorAll('[data-dedupe-total-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('editDedupeTotalDataId').value = btn.dataset.dedupeTotalEdit || ''; + document.getElementById('editDedupeTotalDataValue').value = (btn.dataset.value || '').replace(/"/g, '"'); + document.getElementById('msgEditDedupeTotalData').textContent = ''; + document.getElementById('msgEditDedupeTotalData').className = 'msg'; + document.getElementById('editDedupeTotalDataModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-dedupe-total-delete]').forEach(function (btn) { + btn.onclick = function () { + var value = (btn.dataset.value || '').replace(/"/g, '"'); + if (!confirm('确定删除总数据“' + value + '”吗?')) return; + fetch('/api/admin/dedupe-total-data/' + btn.dataset.dedupeTotalDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadDedupeTotalData(dedupeTotalDataPage); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + document.getElementById('btnSearchDedupeTotalData').onclick = function () { loadDedupeTotalData(1); }; + var dedupeImportPollTimer = null; + var dedupeDeleteImportPollTimer = null; + function stopDedupeImportProgress() { + if (dedupeImportPollTimer) { + clearInterval(dedupeImportPollTimer); + dedupeImportPollTimer = null; + } + } + function stopDedupeDeleteImportProgress() { + if (dedupeDeleteImportPollTimer) { + clearInterval(dedupeDeleteImportPollTimer); + dedupeDeleteImportPollTimer = null; + } + } + function setDedupeImportProgress(percent, text) { + var wrap = document.getElementById('dedupeTotalDataProgressWrap'); + var fill = document.getElementById('dedupeTotalDataProgressFill'); + var textEl = document.getElementById('dedupeTotalDataProgressText'); + wrap.style.display = 'block'; + fill.style.width = Math.max(0, Math.min(100, percent || 0)) + '%'; + textEl.textContent = text || ''; + } + function setDedupeDeleteImportProgress(percent, text) { + var wrap = document.getElementById('dedupeTotalDataDeleteProgressWrap'); + var fill = document.getElementById('dedupeTotalDataDeleteProgressFill'); + var textEl = document.getElementById('dedupeTotalDataDeleteProgressText'); + wrap.style.display = 'block'; + fill.style.width = Math.max(0, Math.min(100, percent || 0)) + '%'; + textEl.textContent = text || ''; + } + function pollDedupeImport(importId) { + stopDedupeImportProgress(); + function tick() { + fetch('/api/admin/dedupe-total-data/import/' + encodeURIComponent(importId)) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = res.error || '查询导入进度失败'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + return; + } + var progress = res.progress || {}; + var totalRows = progress.total_rows || 0; + var processedRows = progress.processed_rows || 0; + var percent = totalRows > 0 ? Math.round(processedRows * 100 / totalRows) : 0; + setDedupeImportProgress(percent, '处理中:已处理 ' + processedRows + ' / ' + totalRows + ',新增 ' + (progress.inserted_count || 0) + ',跳过 ' + (progress.skipped_count || 0)); + if (progress.status === 'success') { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = '导入成功:总行数 ' + (progress.total_rows || 0) + ',ASIN 数量 ' + (progress.asin_count || 0) + ',新增 ' + (progress.inserted_count || 0) + ',跳过 ' + (progress.skipped_count || 0); + document.getElementById('msgDedupeTotalData').className = 'msg ok'; + loadDedupeTotalData(1); + } else if (progress.status === 'failed') { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = progress.error_message || '导入失败'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + } + }) + .catch(function () { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = '查询导入进度失败'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + }); + } + tick(); + dedupeImportPollTimer = setInterval(tick, 1000); + } + function pollDedupeDeleteImport(importId) { + stopDedupeDeleteImportProgress(); + function tick() { + fetch('/api/admin/dedupe-total-data/delete-import/' + encodeURIComponent(importId)) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = res.error || '查询删除进度失败'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + return; + } + var progress = res.progress || {}; + var totalRows = progress.total_rows || 0; + var processedRows = progress.processed_rows || 0; + var percent = totalRows > 0 ? Math.round(processedRows * 100 / totalRows) : 0; + setDedupeDeleteImportProgress(percent, '处理中:已处理 ' + processedRows + ' / ' + totalRows + ',删除 ' + (progress.deleted_count || 0) + ',跳过 ' + (progress.skipped_count || 0)); + if (progress.status === 'success') { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = '删除成功:总行数 ' + (progress.total_rows || 0) + ',ASIN 数量 ' + (progress.asin_count || 0) + ',删除 ' + (progress.deleted_count || 0) + ',跳过 ' + (progress.skipped_count || 0); + document.getElementById('msgDeleteDedupeTotalData').className = 'msg ok'; + loadDedupeTotalData(1); + } else if (progress.status === 'failed') { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = progress.error_message || '删除失败'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + } + }) + .catch(function () { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = '查询删除进度失败'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + }); + } + tick(); + dedupeDeleteImportPollTimer = setInterval(tick, 1000); + } + + document.getElementById('btnAddDedupeTotalData').onclick = function () { + var fileInput = document.getElementById('dedupeTotalDataFile'); + var msgEl = document.getElementById('msgDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + stopDedupeImportProgress(); + document.getElementById('dedupeTotalDataProgressWrap').style.display = 'none'; + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '请选择 Excel 文件'; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + var lowerName = (file.name || '').toLowerCase(); + if (!(lowerName.endsWith('.xlsx') || lowerName.endsWith('.xls'))) { + msgEl.textContent = '仅支持 .xlsx 或 .xls 文件'; + msgEl.classList.add('err'); + return; + } + var formData = new FormData(); + formData.append('file', file); + var xhr = new XMLHttpRequest(); + xhr.open('POST', '/api/admin/dedupe-total-data/import', true); + xhr.upload.onprogress = function (event) { + if (event.lengthComputable) { + var percent = Math.round(event.loaded * 100 / event.total); + setDedupeImportProgress(percent, '上传中:' + percent + '%'); + } + }; + xhr.onreadystatechange = function () { + if (xhr.readyState !== 4) return; + if (xhr.status < 200 || xhr.status >= 300) { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + return; + } + var res; + try { res = JSON.parse(xhr.responseText || '{}'); } catch (e) { res = { success: false, error: '返回格式错误' }; } + if (!res.success) { + msgEl.textContent = res.error || '导入失败'; + msgEl.className = 'msg err'; + return; + } + setDedupeImportProgress(100, '上传完成,后端处理中...'); + pollDedupeImport(res.import_id); + fileInput.value = ''; + }; + xhr.onerror = function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }; + xhr.send(formData); + }; + document.getElementById('btnDeleteImportDedupeTotalData').onclick = function () { + var fileInput = document.getElementById('dedupeTotalDataDeleteFile'); + var msgEl = document.getElementById('msgDeleteDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + stopDedupeDeleteImportProgress(); + document.getElementById('dedupeTotalDataDeleteProgressWrap').style.display = 'none'; + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '请选择 Excel 文件'; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + var lowerName = (file.name || '').toLowerCase(); + if (!(lowerName.endsWith('.xlsx') || lowerName.endsWith('.xls'))) { + msgEl.textContent = '仅支持 .xlsx 或 .xls 文件'; + msgEl.classList.add('err'); + return; + } + if (!confirm('确定按 Excel 中的 ASIN 批量删除匹配的总数据吗?')) { + return; + } + var formData = new FormData(); + formData.append('file', file); + var xhr = new XMLHttpRequest(); + xhr.open('POST', '/api/admin/dedupe-total-data/delete-import', true); + xhr.upload.onprogress = function (event) { + if (event.lengthComputable) { + var percent = Math.round(event.loaded * 100 / event.total); + setDedupeDeleteImportProgress(percent, '上传中:' + percent + '%'); + } + }; + xhr.onreadystatechange = function () { + if (xhr.readyState !== 4) return; + if (xhr.status < 200 || xhr.status >= 300) { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + return; + } + var res; + try { res = JSON.parse(xhr.responseText || '{}'); } catch (e) { res = { success: false, error: '返回格式错误' }; } + if (!res.success) { + msgEl.textContent = res.error || '删除失败'; + msgEl.className = 'msg err'; + return; + } + setDedupeDeleteImportProgress(100, '上传完成,后端处理中...'); + pollDedupeDeleteImport(res.import_id); + fileInput.value = ''; + }; + xhr.onerror = function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }; + xhr.send(formData); + }; + document.getElementById('btnSaveDedupeTotalData').onclick = function () { + var itemId = document.getElementById('editDedupeTotalDataId').value; + var value = (document.getElementById('editDedupeTotalDataValue').value || '').trim(); + var msgEl = document.getElementById('msgEditDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!value) { + msgEl.textContent = '请填写总数据值'; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/dedupe-total-data/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ data_value: value }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editDedupeTotalDataModal').classList.remove('show'); + loadDedupeTotalData(dedupeTotalDataPage); + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }); + }; + document.getElementById('btnCloseEditDedupeTotalData').onclick = function () { + document.getElementById('editDedupeTotalDataModal').classList.remove('show'); + }; + + // ========== 店铺密钥管理 ========== + var shopKeyPage = 1, shopKeyPageSize = 15; + function buildShopKeyQuery(page) { + return 'page=' + (page || 1) + '&page_size=' + shopKeyPageSize; + } + function loadShopKeys(page) { + shopKeyPage = page || 1; + fetch('/api/admin/shop-keys?' + buildShopKeyQuery(shopKeyPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('shopKeyListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无店铺密钥'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (shopKeyPage - 1) * shopKeyPageSize + index + 1; + return '' + rowNo + '' + (item.ziniao_account_name || '') + '' + (item.ziniao_token || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('shopKeyPagination', res.total, res.page, res.page_size, loadShopKeys); + bindShopKeyActions(); + }) + .catch(function () { + document.getElementById('shopKeyListBody').innerHTML = '请求失败'; + }); + } + function bindShopKeyActions() { + document.querySelectorAll('[data-shop-key-edit]').forEach(function (btn) { + btn.onclick = function () { + var item = {}; + try { item = JSON.parse((btn.dataset.shopKey || '').replace(/"/g, '"')); } catch (e) { item = {}; } + document.getElementById('editShopKeyId').value = item.id || ''; + document.getElementById('editShopKeyZiniaoAccountName').value = item.ziniao_account_name || ''; + document.getElementById('editShopKeyZiniaoToken').value = item.ziniao_token || ''; + document.getElementById('msgEditShopKey').textContent = ''; + document.getElementById('msgEditShopKey').className = 'msg'; + document.getElementById('editShopKeyModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-shop-key-delete]').forEach(function (btn) { + btn.onclick = function () { + var name = (btn.dataset.ziniaoAccountName || '').replace(/"/g, '"'); + if (!confirm('确定删除店铺密钥“' + name + '”吗?')) return; + fetch('/api/admin/shop-key/' + btn.dataset.shopKeyDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadShopKeys(shopKeyPage); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + document.getElementById('btnCreateShopKey').onclick = function () { + var ziniaoAccountName = (document.getElementById('shopKeyZiniaoAccountName').value || '').trim(); + var ziniaoToken = (document.getElementById('shopKeyZiniaoToken').value || '').trim(); + var msgEl = document.getElementById('msgShopKey'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!ziniaoAccountName || !ziniaoToken) { + msgEl.textContent = '请完整填写紫鸟账号名称、紫鸟令牌'; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-key', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ziniao_account_name: ziniaoAccountName, + ziniao_token: ziniaoToken + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('shopKeyZiniaoAccountName').value = ''; + document.getElementById('shopKeyZiniaoToken').value = ''; + msgEl.textContent = res.msg || '创建成功'; + msgEl.className = 'msg ok'; + loadShopKeys(1); + } else { + msgEl.textContent = res.error || '创建失败'; + msgEl.className = 'msg err'; + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }); + }; + document.getElementById('btnSaveShopKey').onclick = function () { + var itemId = document.getElementById('editShopKeyId').value; + var ziniaoAccountName = (document.getElementById('editShopKeyZiniaoAccountName').value || '').trim(); + var ziniaoToken = (document.getElementById('editShopKeyZiniaoToken').value || '').trim(); + var msgEl = document.getElementById('msgEditShopKey'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!ziniaoAccountName || !ziniaoToken) { + msgEl.textContent = '请完整填写紫鸟账号名称、紫鸟令牌'; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-key/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ziniao_account_name: ziniaoAccountName, + ziniao_token: ziniaoToken + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editShopKeyModal').classList.remove('show'); + loadShopKeys(shopKeyPage); + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.classList.add('err'); + }); + }; + document.getElementById('btnCloseEditShopKey').onclick = function () { + document.getElementById('editShopKeyModal').classList.remove('show'); + }; + + // ========== 店铺管理 ========== + var shopManagePage = 1, shopManagePageSize = 15; + var shopManageGroups = []; + + function buildShopManageQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + shopManagePageSize; + var groupId = (document.getElementById('shopManageFilterGroupId').value || '').trim(); + var shopName = (document.getElementById('shopManageFilterShopName').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + return query; + } + + function refreshShopGroupSelects(selectedCreateId, selectedEditId) { + var createSel = document.getElementById('shopManageGroupSelect'); + var editSel = document.getElementById('editShopManageGroupSelect'); + var filterSel = document.getElementById('shopManageFilterGroupId'); + var skipCreateSel = document.getElementById('skipPriceAsinGroupSelect'); + var skipFilterSel = document.getElementById('skipPriceAsinFilterGroupId'); + var chooseSkipShopSel = document.getElementById('chooseSkipPriceAsinShopGroupId'); + var selectedFilterId = filterSel ? filterSel.value : ''; + var selectedSkipCreateId = skipCreateSel ? skipCreateSel.value : ''; + var selectedSkipFilterId = skipFilterSel ? skipFilterSel.value : ''; + var selectedChooseSkipShopId = chooseSkipShopSel ? chooseSkipShopSel.value : ''; + var createOpts = ['']; + var filterOpts = ['']; + shopManageGroups.forEach(function (g) { + var option = ''; + createOpts.push(option); + filterOpts.push(option); + }); + createSel.innerHTML = createOpts.join(''); + editSel.innerHTML = createOpts.join(''); + if (skipCreateSel) skipCreateSel.innerHTML = createOpts.join(''); + if (filterSel) filterSel.innerHTML = filterOpts.join(''); + if (skipFilterSel) skipFilterSel.innerHTML = filterOpts.join(''); + if (chooseSkipShopSel) chooseSkipShopSel.innerHTML = filterOpts.join(''); + if (selectedCreateId != null) createSel.value = String(selectedCreateId); + if (selectedEditId != null) editSel.value = String(selectedEditId); + if (filterSel && selectedFilterId) filterSel.value = selectedFilterId; + if (skipCreateSel && selectedSkipCreateId) skipCreateSel.value = selectedSkipCreateId; + if (skipFilterSel && selectedSkipFilterId) skipFilterSel.value = selectedSkipFilterId; + if (chooseSkipShopSel && selectedChooseSkipShopId) chooseSkipShopSel.value = selectedChooseSkipShopId; + } + + function loadShopManageGroups(selectedCreateId, selectedEditId) { + return fetch('/api/admin/shop-manage-groups') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) throw new Error(res.error || '加载分组失败'); + shopManageGroups = res.items || []; + refreshShopGroupSelects(selectedCreateId, selectedEditId); + return shopManageGroups; + }) + .catch(function () { + shopManageGroups = []; + refreshShopGroupSelects(); + return []; + }); + } + + function openShopManageGroupModal() { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + document.getElementById('msgShopManageGroup').textContent = ''; + document.getElementById('msgShopManageGroup').className = 'msg'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + document.getElementById('shopManageGroupModal').classList.add('show'); + }); + } + + function renderShopManageGroupRows() { + var tbody = document.getElementById('shopManageGroupListBody'); + if (!shopManageGroups.length) { + tbody.innerHTML = '暂无分组'; + return; + } + tbody.innerHTML = shopManageGroups.map(function (item, index) { + return '' + (index + 1) + '' + (item.group_name || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + + document.querySelectorAll('[data-shop-group-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('shopManageGroupEditId').value = btn.dataset.shopGroupEdit; + document.getElementById('shopManageGroupInput').value = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + }; + }); + + document.querySelectorAll('[data-shop-group-delete]').forEach(function (btn) { + btn.onclick = function () { + var gid = btn.dataset.shopGroupDelete; + var gname = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + if (!confirm('确定删除分组“' + gname + '”吗?')) return; + fetch('/api/admin/shop-manage-group/' + gid, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + alert(res.error || '删除失败'); + return; + } + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }); + }; + }); + } + + function loadShopManage(page) { + shopManagePage = page || 1; + fetch('/api/admin/shop-manages?' + buildShopManageQuery(shopManagePage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('shopManageListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无店铺'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (shopManagePage - 1) * shopManagePageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + (item.mall_name || '') + '' + (item.account || '') + '' + (item.password || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('shopManagePagination', res.total, res.page, res.page_size, loadShopManage); + bindShopManageActions(); + }) + .catch(function () { + document.getElementById('shopManageListBody').innerHTML = '请求失败'; + }); + } + + function bindShopManageActions() { + document.querySelectorAll('[data-shop-manage-edit]').forEach(function (btn) { + btn.onclick = function () { + var item = {}; + try { item = JSON.parse((btn.dataset.shopManage || '').replace(/"/g, '"')); } catch (e) { item = {}; } + document.getElementById('editShopManageId').value = item.id || ''; + document.getElementById('editShopManageShopName').value = item.shop_name || ''; + document.getElementById('editShopManageMallName').value = item.mall_name || ''; + document.getElementById('editShopManageAccount').value = item.account || ''; + document.getElementById('editShopManagePassword').value = item.password || ''; + document.getElementById('msgEditShopManage').textContent = ''; + document.getElementById('msgEditShopManage').className = 'msg'; + loadShopManageGroups(null, item.group_id).then(function () { + document.getElementById('editShopManageModal').classList.add('show'); + }); + }; + }); + document.querySelectorAll('[data-shop-manage-delete]').forEach(function (btn) { + btn.onclick = function () { + var name = (btn.dataset.shopManageName || '').replace(/"/g, '"'); + if (!confirm('确定删除店铺“' + name + '”吗?')) return; + fetch('/api/admin/shop-manage/' + btn.dataset.shopManageDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadShopManage(shopManagePage); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + + document.getElementById('btnManageShopGroups').onclick = openShopManageGroupModal; + document.getElementById('btnManageShopGroupsFromEdit').onclick = openShopManageGroupModal; + document.getElementById('btnSearchShopManage').onclick = function () { + loadShopManage(1); + }; + document.getElementById('shopManageFilterShopName').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadShopManage(1); + } + }); + document.getElementById('btnCloseShopManageGroupModal').onclick = function () { + document.getElementById('shopManageGroupModal').classList.remove('show'); + }; + document.getElementById('btnCancelShopManageGroupEdit').onclick = function () { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + }; + document.getElementById('btnSaveShopManageGroup').onclick = function () { + var editId = (document.getElementById('shopManageGroupEditId').value || '').trim(); + var groupName = (document.getElementById('shopManageGroupInput').value || '').trim(); + var msgEl = document.getElementById('msgShopManageGroup'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupName) { + msgEl.textContent = '请输入分组名称'; + msgEl.className = 'msg err'; + return; + } + var method = editId ? 'PUT' : 'POST'; + var url = editId ? ('/api/admin/shop-manage-group/' + editId) : '/api/admin/shop-manage-group'; + fetch(url, { + method: method, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_name: groupName }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '保存失败'; + msgEl.className = 'msg err'; + return; + } + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + msgEl.textContent = res.msg || '保存成功'; + msgEl.className = 'msg ok'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }); + }; + + function refreshShopGroupSelects(selectedCreateId, selectedEditId) { + var createSel = document.getElementById('shopManageGroupSelect'); + var editSel = document.getElementById('editShopManageGroupSelect'); + var filterSel = document.getElementById('shopManageFilterGroupId'); + var skipCreateSel = document.getElementById('skipPriceAsinGroupSelect'); + var skipFilterSel = document.getElementById('skipPriceAsinFilterGroupId'); + var chooseSkipShopSel = document.getElementById('chooseSkipPriceAsinShopGroupId'); + var selectedFilterId = filterSel ? filterSel.value : ''; + var selectedSkipCreateId = skipCreateSel ? skipCreateSel.value : ''; + var selectedSkipFilterId = skipFilterSel ? skipFilterSel.value : ''; + var selectedChooseSkipShopId = chooseSkipShopSel ? chooseSkipShopSel.value : ''; + var createOpts = ['']; + var filterOpts = ['']; + shopManageGroups.forEach(function (g) { + var option = ''; + createOpts.push(option); + filterOpts.push(option); + }); + createSel.innerHTML = createOpts.join(''); + editSel.innerHTML = createOpts.join(''); + if (skipCreateSel) skipCreateSel.innerHTML = createOpts.join(''); + if (filterSel) filterSel.innerHTML = filterOpts.join(''); + if (skipFilterSel) skipFilterSel.innerHTML = filterOpts.join(''); + if (chooseSkipShopSel) chooseSkipShopSel.innerHTML = filterOpts.join(''); + if (selectedCreateId != null) createSel.value = String(selectedCreateId); + if (selectedEditId != null) editSel.value = String(selectedEditId); + if (filterSel && selectedFilterId) filterSel.value = selectedFilterId; + if (skipCreateSel && selectedSkipCreateId) skipCreateSel.value = selectedSkipCreateId; + if (skipFilterSel && selectedSkipFilterId) skipFilterSel.value = selectedSkipFilterId; + if (chooseSkipShopSel && selectedChooseSkipShopId) chooseSkipShopSel.value = selectedChooseSkipShopId; + } + + function loadShopManageGroups(selectedCreateId, selectedEditId) { + return fetch('/api/admin/shop-manage-groups') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) throw new Error(res.error || '加载分组失败'); + shopManageGroups = res.items || []; + refreshShopGroupSelects(selectedCreateId, selectedEditId); + return shopManageGroups; + }) + .catch(function () { + shopManageGroups = []; + refreshShopGroupSelects(); + return []; + }); + } + + function resetShopManageGroupForm() { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + document.getElementById('msgShopManageGroup').textContent = ''; + document.getElementById('msgShopManageGroup').className = 'msg'; + refreshShopManageGroupUserSelect(''); + } + + function openShopManageGroupModal() { + resetShopManageGroupForm(); + loadUserOptions() + .then(function () { return loadShopManageGroups(); }) + .then(function () { + renderShopManageGroupRows(); + document.getElementById('shopManageGroupModal').classList.add('show'); + }); + } + + function renderShopManageGroupRows() { + var tbody = document.getElementById('shopManageGroupListBody'); + if (!shopManageGroups.length) { + tbody.innerHTML = '暂无分组'; + return; + } + tbody.innerHTML = shopManageGroups.map(function (item, index) { + return '' + (index + 1) + '' + (item.group_name || '') + '' + (item.username || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + + document.querySelectorAll('[data-shop-group-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('shopManageGroupEditId').value = btn.dataset.shopGroupEdit; + refreshShopManageGroupUserSelect(btn.dataset.shopGroupUserId || ''); + }; + }); + + document.querySelectorAll('[data-shop-group-delete]').forEach(function (btn) { + btn.onclick = function () { + var gid = btn.dataset.shopGroupDelete; + var gname = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + if (!confirm('确定删除分组“' + gname + '”吗?')) return; + fetch('/api/admin/shop-manage-group/' + gid, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + alert(res.error || '删除失败'); + return; + } + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }); + }; + }); + } + + document.getElementById('shopManageGroupUserSelect').onchange = syncShopManageGroupNameWithUser; + document.getElementById('btnManageShopGroups').onclick = openShopManageGroupModal; + document.getElementById('btnManageShopGroupsFromEdit').onclick = openShopManageGroupModal; + document.getElementById('btnManageSkipPriceAsinGroups').onclick = openShopManageGroupModal; + document.getElementById('btnCloseShopManageGroupModal').onclick = function () { + document.getElementById('shopManageGroupModal').classList.remove('show'); + }; + document.getElementById('btnCancelShopManageGroupEdit').onclick = resetShopManageGroupForm; + document.getElementById('btnSaveShopManageGroup').onclick = function () { + var editId = (document.getElementById('shopManageGroupEditId').value || '').trim(); + var groupName = (document.getElementById('shopManageGroupInput').value || '').trim(); + var userId = (document.getElementById('shopManageGroupUserSelect').value || '').trim(); + var msgEl = document.getElementById('msgShopManageGroup'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!userId || !groupName) { + msgEl.textContent = '请选择关联用户'; + msgEl.className = 'msg err'; + return; + } + var method = editId ? 'PUT' : 'POST'; + var url = editId ? ('/api/admin/shop-manage-group/' + editId) : '/api/admin/shop-manage-group'; + fetch(url, { + method: method, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_name: groupName, user_id: Number(userId) }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '保存失败'; + msgEl.className = 'msg err'; + return; + } + resetShopManageGroupForm(); + msgEl.textContent = res.msg || '保存成功'; + msgEl.className = 'msg ok'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }); + }; + + document.getElementById('btnCreateShopManage').onclick = function () { + var groupId = (document.getElementById('shopManageGroupSelect').value || '').trim(); + var shopName = (document.getElementById('shopManageShopName').value || '').trim(); + var mallName = (document.getElementById('shopManageMallName').value || '').trim(); + var account = (document.getElementById('shopManageAccount').value || '').trim(); + var password = (document.getElementById('shopManagePassword').value || '').trim(); + var msgEl = document.getElementById('msgShopManage'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !mallName || !account || !password) { + msgEl.textContent = '请完整填写分组、店铺名、店铺商城名、账号、密码'; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-manage', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_id: Number(groupId), shop_name: shopName, mall_name: mallName, account: account, password: password }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('shopManageGroupSelect').value = ''; + document.getElementById('shopManageShopName').value = ''; + document.getElementById('shopManageMallName').value = ''; + document.getElementById('shopManageAccount').value = ''; + document.getElementById('shopManagePassword').value = ''; + msgEl.textContent = res.msg || '创建成功'; + msgEl.className = 'msg ok'; + loadShopManage(1); + } else { + msgEl.textContent = res.error || '创建失败'; + msgEl.className = 'msg err'; + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }); + }; + + document.getElementById('btnSaveShopManage').onclick = function () { + var itemId = document.getElementById('editShopManageId').value; + var groupId = (document.getElementById('editShopManageGroupSelect').value || '').trim(); + var shopName = (document.getElementById('editShopManageShopName').value || '').trim(); + var mallName = (document.getElementById('editShopManageMallName').value || '').trim(); + var account = (document.getElementById('editShopManageAccount').value || '').trim(); + var password = (document.getElementById('editShopManagePassword').value || '').trim(); + var msgEl = document.getElementById('msgEditShopManage'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !mallName || !account || !password) { + msgEl.textContent = '请完整填写分组、店铺名、店铺商城名、账号、密码'; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-manage/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_id: Number(groupId), shop_name: shopName, mall_name: mallName, account: account, password: password }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editShopManageModal').classList.remove('show'); + loadShopManage(shopManagePage); + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.classList.add('err'); + }); + }; + document.getElementById('btnCloseEditShopManage').onclick = function () { + document.getElementById('editShopManageModal').classList.remove('show'); + }; + + // ========== 版本管理 ========== + // ========== 跳过跟价 ASIN ========== + var skipPriceAsinPage = 1, skipPriceAsinPageSize = 15; + var chooseSkipPriceAsinShopPage = 1, chooseSkipPriceAsinShopPageSize = 10; + var skipPriceCountryColumns = [ + { code: 'DE', field: 'asin_de', label: '德国' }, + { code: 'UK', field: 'asin_uk', label: '英国' }, + { code: 'FR', field: 'asin_fr', label: '法国' }, + { code: 'IT', field: 'asin_it', label: '意大利' }, + { code: 'ES', field: 'asin_es', label: '西班牙' } + ]; + function buildChooseSkipPriceAsinShopQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + chooseSkipPriceAsinShopPageSize; + var groupId = (document.getElementById('chooseSkipPriceAsinShopGroupId').value || '').trim(); + var shopName = (document.getElementById('chooseSkipPriceAsinShopKeyword').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + return query; + } + function loadChooseSkipPriceAsinShops(page) { + chooseSkipPriceAsinShopPage = page || 1; + fetch('/api/admin/shop-manages?' + buildChooseSkipPriceAsinShopQuery(chooseSkipPriceAsinShopPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('chooseSkipPriceAsinShopListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (!items.length) { + tbody.innerHTML = '暂无店铺'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (chooseSkipPriceAsinShopPage - 1) * chooseSkipPriceAsinShopPageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + (item.mall_name || '') + '' + (item.account || '') + '' + + '' + + ''; + }).join(''); + } + renderPagination('chooseSkipPriceAsinShopPagination', res.total, res.page, res.page_size, loadChooseSkipPriceAsinShops); + bindChooseSkipPriceAsinShopActions(); + }) + .catch(function () { + document.getElementById('chooseSkipPriceAsinShopListBody').innerHTML = '请求失败'; + }); + } + function bindChooseSkipPriceAsinShopActions() { + document.querySelectorAll('[data-choose-skip-price-asin-shop]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('skipPriceAsinShopName').value = (btn.dataset.shopName || '').replace(/"/g, '"'); + if (!document.getElementById('skipPriceAsinGroupSelect').value && btn.dataset.groupId) { + document.getElementById('skipPriceAsinGroupSelect').value = btn.dataset.groupId; + } + document.getElementById('chooseSkipPriceAsinShopModal').classList.remove('show'); + }; + }); + } + function openChooseSkipPriceAsinShopModal() { + var currentGroupId = (document.getElementById('skipPriceAsinGroupSelect').value || '').trim(); + if (currentGroupId) { + document.getElementById('chooseSkipPriceAsinShopGroupId').value = currentGroupId; + } + document.getElementById('chooseSkipPriceAsinShopKeyword').value = (document.getElementById('skipPriceAsinShopName').value || '').trim(); + document.getElementById('chooseSkipPriceAsinShopModal').classList.add('show'); + loadChooseSkipPriceAsinShops(1); + } + function setupSkipPriceAsinShopPicker() { + var input = document.getElementById('skipPriceAsinShopName'); + var button = document.getElementById('btnChooseSkipPriceAsinShop'); + if (!input || !button) return; + var inputParent = input.parentNode; + if (inputParent && inputParent.style && inputParent.style.display === 'flex') return; + var legacyWrap = button.parentNode; + var wrapper = document.createElement('div'); + wrapper.style.display = 'flex'; + wrapper.style.gap = '8px'; + wrapper.style.alignItems = 'center'; + input.parentNode.insertBefore(wrapper, input); + wrapper.appendChild(input); + wrapper.appendChild(button); + button.style.whiteSpace = 'nowrap'; + button.style.marginTop = '0'; + if (legacyWrap && legacyWrap !== wrapper) { + legacyWrap.style.display = 'none'; + } + } + function getSelectedSkipPriceCountries() { + return Array.from(document.getElementById('skipPriceAsinCountries').selectedOptions).map(function (option) { + return option.value; + }); + } + function renderSkipPriceAsinInputs() { + var container = document.getElementById('skipPriceAsinInputs'); + var selectedCountries = getSelectedSkipPriceCountries(); + var existingValues = {}; + container.querySelectorAll('[data-skip-price-country-input]').forEach(function (input) { + existingValues[input.getAttribute('data-skip-price-country-input')] = input.value; + }); + if (!selectedCountries.length) { + container.innerHTML = '
请选择国家后输入 ASIN
'; + return; + } + container.innerHTML = selectedCountries.map(function (countryCode) { + var country = skipPriceCountryColumns.find(function (item) { return item.code === countryCode; }); + var label = country ? country.label : countryCode; + var value = existingValues[countryCode] || ''; + return '
' + + '' + label + '' + + '' + + '
'; + }).join(''); + } + function collectSkipPriceAsinMappings(countries) { + var mappings = {}; + for (var i = 0; i < countries.length; i++) { + var countryCode = countries[i]; + var input = document.querySelector('[data-skip-price-country-input="' + countryCode + '"]'); + var asin = input ? (input.value || '').trim().toUpperCase() : ''; + if (!asin) { + var country = skipPriceCountryColumns.find(function (item) { return item.code === countryCode; }); + var label = country ? country.label : countryCode; + throw new Error(label + ' ASIN 不能为空'); + } + mappings[countryCode] = asin; + } + return mappings; + } + function buildSkipPriceAsinQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + skipPriceAsinPageSize; + var groupId = (document.getElementById('skipPriceAsinFilterGroupId').value || '').trim(); + var shopName = (document.getElementById('skipPriceAsinFilterShopName').value || '').trim(); + var asin = (document.getElementById('skipPriceAsinFilterAsin').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + if (asin) query += '&asin=' + encodeURIComponent(asin); + return query; + } + function renderSkipPriceAsinCell(item, country) { + var value = item[country.field] || ''; + if (!value) return '-'; + return '
' + + '' + value + '' + + '' + + '' + + '
'; + } + function bindSkipPriceAsinActions() { + document.querySelectorAll('[data-skip-price-asin-edit]').forEach(function (btn) { + btn.onclick = function () { + var shopName = (btn.dataset.shopName || '').replace(/"/g, '"'); + var countryCode = btn.dataset.country || ''; + var currentAsin = (btn.dataset.asin || '').replace(/"/g, '"'); + var nextAsin = prompt('请输入店铺“' + shopName + '”在 ' + countryCode + ' 的 ASIN', currentAsin); + if (nextAsin === null) return; + nextAsin = (nextAsin || '').trim(); + if (!nextAsin) { + alert('ASIN 不能为空'); + return; + } + fetch('/api/admin/skip-price-asin/' + btn.dataset.skipPriceAsinEdit + '/country/' + countryCode, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ asin: nextAsin }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) loadSkipPriceAsin(skipPriceAsinPage); + else alert(res.error || '保存失败'); + }); + }; + }); + document.querySelectorAll('[data-skip-price-asin-delete]').forEach(function (btn) { + btn.onclick = function () { + var shopName = (btn.dataset.shopName || '').replace(/"/g, '"'); + var countryCode = btn.dataset.country || ''; + if (!confirm('确定删除店铺“' + shopName + '”在 ' + countryCode + ' 的 ASIN 吗?')) return; + fetch('/api/admin/skip-price-asin/' + btn.dataset.skipPriceAsinDelete + '/country/' + countryCode, { + method: 'DELETE' + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) loadSkipPriceAsin(skipPriceAsinPage); + else alert(res.error || '删除失败'); + }); + }; + }); + } + function loadSkipPriceAsin(page) { + skipPriceAsinPage = page || 1; + fetch('/api/admin/skip-price-asins?' + buildSkipPriceAsinQuery(skipPriceAsinPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('skipPriceAsinListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无数据'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (skipPriceAsinPage - 1) * skipPriceAsinPageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + + skipPriceCountryColumns.map(function (country) { + return '' + renderSkipPriceAsinCell(item, country) + ''; + }).join('') + + ''; + }).join(''); + } + renderPagination('skipPriceAsinPagination', res.total, res.page, res.page_size, loadSkipPriceAsin); + bindSkipPriceAsinActions(); + }) + .catch(function () { + document.getElementById('skipPriceAsinListBody').innerHTML = '请求失败'; + }); + } + document.getElementById('btnManageSkipPriceAsinGroups').onclick = openShopManageGroupModal; + document.getElementById('btnChooseSkipPriceAsinShop').onclick = openChooseSkipPriceAsinShopModal; + document.getElementById('btnSearchChooseSkipPriceAsinShop').onclick = function () { + loadChooseSkipPriceAsinShops(1); + }; + document.getElementById('chooseSkipPriceAsinShopGroupId').onchange = function () { + loadChooseSkipPriceAsinShops(1); + }; + document.getElementById('chooseSkipPriceAsinShopKeyword').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadChooseSkipPriceAsinShops(1); + } + }); + document.getElementById('btnCloseChooseSkipPriceAsinShopModal').onclick = function () { + document.getElementById('chooseSkipPriceAsinShopModal').classList.remove('show'); + }; + document.getElementById('skipPriceAsinCountries').addEventListener('change', renderSkipPriceAsinInputs); + document.getElementById('btnSearchSkipPriceAsin').onclick = function () { + loadSkipPriceAsin(1); + }; + document.getElementById('skipPriceAsinFilterShopName').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadSkipPriceAsin(1); + } + }); + document.getElementById('skipPriceAsinFilterAsin').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadSkipPriceAsin(1); + } + }); + document.getElementById('btnCreateSkipPriceAsin').onclick = function () { + var groupId = (document.getElementById('skipPriceAsinGroupSelect').value || '').trim(); + var shopName = (document.getElementById('skipPriceAsinShopName').value || '').trim(); + var countries = getSelectedSkipPriceCountries(); + var msgEl = document.getElementById('msgSkipPriceAsin'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !countries.length) { + msgEl.textContent = '请完整填写分组、店铺名、国家和 ASIN'; + msgEl.className = 'msg err'; + return; + } + var asinMappings = {}; + try { + asinMappings = collectSkipPriceAsinMappings(countries); + } catch (err) { + msgEl.textContent = err.message || '请输入 ASIN'; + msgEl.className = 'msg err'; + return; + } + var fallbackAsin = ''; + Object.keys(asinMappings).some(function (countryCode) { + fallbackAsin = asinMappings[countryCode] || ''; + return !!fallbackAsin; + }); + fetch('/api/admin/skip-price-asin', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + group_id: Number(groupId), + shop_name: shopName, + countries: countries, + asin: fallbackAsin, + asin_mappings: asinMappings + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '保存失败'; + msgEl.className = 'msg err'; + return; + } + document.getElementById('skipPriceAsinGroupSelect').value = ''; + document.getElementById('skipPriceAsinShopName').value = ''; + Array.from(document.getElementById('skipPriceAsinCountries').options).forEach(function (option) { + option.selected = false; + }); + renderSkipPriceAsinInputs(); + msgEl.textContent = res.msg || '保存成功'; + msgEl.className = 'msg ok'; + loadSkipPriceAsin(1); + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.className = 'msg err'; + }); + }; + setupSkipPriceAsinShopPicker(); + renderSkipPriceAsinInputs(); + function loadVersions() { + fetch('/api/admin/versions') + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('versionListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '暂无版本记录'; + } else { + tbody.innerHTML = items.map(function (v) { + var url = (v.file_url || '').replace(/"/g, '"'); + return '' + (v.version || '') + '
' + url + '' + (v.created_at || '') + '下载'; + }).join(''); + } + }) + .catch(function () { + document.getElementById('versionListBody').innerHTML = '请求失败'; + }); + } + document.getElementById('btnUploadVersion').onclick = function () { + var version = (document.getElementById('versionNumber').value || '').trim(); + var fileInput = document.getElementById('versionZip'); + var msgEl = document.getElementById('msgVersion'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!version) { + msgEl.textContent = '请填写版本号'; + msgEl.classList.add('err'); + return; + } + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '请选择 zip 压缩包'; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + if (!(file.name || '').toLowerCase().endsWith('.zip')) { + msgEl.textContent = '仅支持 .zip 格式'; + msgEl.classList.add('err'); + return; + } + var formData = new FormData(); + formData.append('version', version); + formData.append('file', file); + msgEl.textContent = '上传中...'; + msgEl.classList.remove('err', 'ok'); + fetch('/api/admin/version', { + method: 'POST', + body: formData + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = '发布成功。版本:' + res.version + ',链接:' + (res.file_url || ''); + msgEl.classList.add('ok'); + document.getElementById('versionNumber').value = ''; + fileInput.value = ''; + loadVersions(); + } else { + msgEl.textContent = res.error || '上传失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '请求失败'; + msgEl.classList.add('err'); + }); + }; + + // ========== 栏目权限配置 ========== + function loadColumns() { + fetch('/api/admin/columns') + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('columnListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + allColumnsList = res.items || []; + if (allColumnsList.length === 0) { + tbody.innerHTML = '暂无菜单,请在上方新增'; + } else { + tbody.innerHTML = allColumnsList.map(function (c) { + return '' + c.id + '' + (c.name || '') + '' + (c.column_key || '') + '' + (c.created_at || '') + '' + + ' ' + + ''; + }).join(''); + } + bindColumnActions(); + }) + .catch(function () { + document.getElementById('columnListBody').innerHTML = '请求失败'; + }); + } + function bindColumnActions() { + document.querySelectorAll('[data-column-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('editColumnId').value = btn.dataset.columnEdit || ''; + document.getElementById('editColumnName').value = (btn.dataset.name || '').replace(/"/g, '"'); + document.getElementById('editColumnKey').value = (btn.dataset.key || '').replace(/"/g, '"'); + document.getElementById('msgEditColumn').textContent = ''; + document.getElementById('editColumnModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-column-delete]').forEach(function (btn) { + btn.onclick = function () { + if (!confirm('确定删除菜单“' + (btn.dataset.name || '').replace(/"/g, '"') + '”吗?')) return; + fetch('/api/admin/column/' + btn.dataset.columnDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadColumns(); loadColumnsForPermission(); loadAdminMenus(getActiveAdminTabName()); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + document.getElementById('btnAddColumn').onclick = function () { + var name = (document.getElementById('columnName').value || '').trim(); + var key = (document.getElementById('columnKey').value || '').trim(); + var msgEl = document.getElementById('msgColumn'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!name) { msgEl.textContent = '请填写菜单名称'; msgEl.classList.add('err'); return; } + if (!key) { + msgEl.textContent = '请填写栏目标识'; msgEl.classList.add('err'); return; + } + fetch('/api/admin/column', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: name, column_key: key }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = res.msg || '新增成功'; + msgEl.classList.add('ok'); + document.getElementById('columnName').value = ''; + document.getElementById('columnKey').value = ''; + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + } else { + msgEl.textContent = res.error || '新增失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { msgEl.textContent = '请求失败'; msgEl.classList.add('err'); }); + }; + document.getElementById('btnSaveColumn').onclick = function () { + var cid = document.getElementById('editColumnId').value; + var name = (document.getElementById('editColumnName').value || '').trim(); + var key = (document.getElementById('editColumnKey').value || '').trim(); + var msgEl = document.getElementById('msgEditColumn'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!name) { msgEl.textContent = '请填写菜单名称'; msgEl.classList.add('err'); return; } + if (!key) { + msgEl.textContent = '请填写栏目标识'; msgEl.classList.add('err'); return; + } + fetch('/api/admin/column/' + cid, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: name, column_key: key }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editColumnModal').classList.remove('show'); + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }); + }; + document.getElementById('btnCloseEditColumn').onclick = function () { + document.getElementById('editColumnModal').classList.remove('show'); + }; + + function loadColumns() { + fetch('/api/admin/columns') + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('columnListBody'); + if (!res.success) { + tbody.innerHTML = '加载失败: ' + (res.error || '') + ''; + return; + } + allColumnsList = res.items || []; + if (allColumnsList.length === 0) { + tbody.innerHTML = '暂无菜单,请先在上方新增'; + } else { + tbody.innerHTML = allColumnsList.map(function (c, index) { + var moveButtons = + ' ' + + ' '; + return '' + c.id + '' + (c.name || '') + '' + (c.column_key || '') + '' + ((c.menu_type || '') === 'admin' ? '后台(admin)' : '软件(app)') + '' + (c.sort_order != null ? c.sort_order : 0) + '' + (c.route_path || '') + '' + (c.created_at || '') + '' + + moveButtons + + ' ' + + ''; + }).join(''); + } + bindColumnActions(); + }) + .catch(function () { + document.getElementById('columnListBody').innerHTML = '请求失败'; + }); + } + function bindColumnActions() { + document.querySelectorAll('[data-column-move-up]').forEach(function (btn) { + btn.onclick = function () { + if (btn.disabled) return; + moveColumnItem(btn.dataset.columnMoveUp, -1, btn); + }; + }); + document.querySelectorAll('[data-column-move-down]').forEach(function (btn) { + btn.onclick = function () { + if (btn.disabled) return; + moveColumnItem(btn.dataset.columnMoveDown, 1, btn); + }; + }); + document.querySelectorAll('[data-column-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('editColumnId').value = btn.dataset.columnEdit || ''; + document.getElementById('editColumnName').value = (btn.dataset.name || '').replace(/"/g, '"'); + document.getElementById('editColumnKey').value = (btn.dataset.key || '').replace(/"/g, '"'); + document.getElementById('editColumnRoutePath').value = (btn.dataset.route || '').replace(/"/g, '"'); + document.getElementById('editColumnMenuType').value = ((btn.dataset.menuType || 'app').replace(/"/g, '"') || 'app'); + document.getElementById('editColumnSortOrder').value = ((btn.dataset.sortOrder || '0').replace(/"/g, '"') || '0'); + document.getElementById('msgEditColumn').textContent = ''; + document.getElementById('editColumnModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-column-delete]').forEach(function (btn) { + btn.onclick = function () { + if (!confirm('确定删除菜单“' + (btn.dataset.name || '').replace(/"/g, '"') + '”吗?')) return; + fetch('/api/admin/column/' + btn.dataset.columnDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadColumns(); loadColumnsForPermission(); loadAdminMenus(getActiveAdminTabName()); } + else { alert(res.error || '删除失败'); } + }); + }; + }); + } + function updateColumnSortOrder(column, sortOrder) { + return fetch('/api/admin/column/' + column.id, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: column.name || '', + column_key: column.column_key || '', + route_path: column.route_path || '', + menu_type: column.menu_type || 'app', + sort_order: sortOrder + }) + }).then(function (r) { return r.json(); }); + } + function moveColumnItem(columnId, delta, triggerBtn) { + var currentIndex = -1; + for (var i = 0; i < allColumnsList.length; i++) { + if (String(allColumnsList[i].id) === String(columnId)) { + currentIndex = i; + break; + } + } + if (currentIndex < 0) return; + var targetIndex = currentIndex + delta; + if (targetIndex < 0 || targetIndex >= allColumnsList.length) return; + var currentItem = allColumnsList[currentIndex]; + var targetItem = allColumnsList[targetIndex]; + if (!currentItem || !targetItem) return; + if (triggerBtn) triggerBtn.disabled = true; + var currentSort = currentItem.sort_order != null ? currentItem.sort_order : (currentIndex + 1); + var targetSort = targetItem.sort_order != null ? targetItem.sort_order : (targetIndex + 1); + Promise.all([ + updateColumnSortOrder(currentItem, targetSort), + updateColumnSortOrder(targetItem, currentSort) + ]).then(function (results) { + var failed = (results || []).find(function (res) { return !res || !res.success; }); + if (failed) { + alert((failed && failed.error) || '排序保存失败'); + return; + } + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + }).catch(function () { + alert('排序保存失败'); + }).finally(function () { + if (triggerBtn) triggerBtn.disabled = false; + }); + } + document.getElementById('btnAddColumn').onclick = function () { + var name = (document.getElementById('columnName').value || '').trim(); + var key = (document.getElementById('columnKey').value || '').trim(); + var routePath = (document.getElementById('columnRoutePath').value || '').trim(); + var sortOrderValue = (document.getElementById('columnSortOrder').value || '').trim(); + var menuType = (document.getElementById('columnMenuType').value || 'admin').trim() || 'admin'; + var sortOrder = sortOrderValue === '' ? null : parseInt(sortOrderValue, 10); + var msgEl = document.getElementById('msgColumn'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!name) { msgEl.textContent = '请填写菜单名称'; msgEl.classList.add('err'); return; } + if (!key) { + msgEl.textContent = '请填写栏目标识'; msgEl.classList.add('err'); return; + } + if (!routePath) { + msgEl.textContent = '请填写菜单路由'; msgEl.classList.add('err'); return; + } + if (sortOrderValue !== '' && isNaN(sortOrder)) { + msgEl.textContent = '排序必须是数字'; msgEl.classList.add('err'); return; + } + fetch('/api/admin/column', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: name, column_key: key, route_path: routePath, menu_type: menuType, sort_order: sortOrder }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = res.msg || '新增成功'; + msgEl.classList.add('ok'); + document.getElementById('columnName').value = ''; + document.getElementById('columnKey').value = ''; + document.getElementById('columnRoutePath').value = ''; + document.getElementById('columnSortOrder').value = ''; + document.getElementById('columnMenuType').value = 'admin'; + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + } else { + msgEl.textContent = res.error || '新增失败'; + msgEl.classList.add('err'); + } + }) + .catch(function () { msgEl.textContent = '请求失败'; msgEl.classList.add('err'); }); + }; + document.getElementById('btnSaveColumn').onclick = function () { + var cid = document.getElementById('editColumnId').value; + var name = (document.getElementById('editColumnName').value || '').trim(); + var key = (document.getElementById('editColumnKey').value || '').trim(); + var routePath = (document.getElementById('editColumnRoutePath').value || '').trim(); + var sortOrderValue = (document.getElementById('editColumnSortOrder').value || '').trim(); + var menuType = (document.getElementById('editColumnMenuType').value || 'admin').trim() || 'admin'; + var sortOrder = sortOrderValue === '' ? null : parseInt(sortOrderValue, 10); + var msgEl = document.getElementById('msgEditColumn'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!name) { msgEl.textContent = '请填写菜单名称'; msgEl.classList.add('err'); return; } + if (!key) { + msgEl.textContent = '请填写栏目标识'; msgEl.classList.add('err'); return; + } + if (!routePath) { + msgEl.textContent = '请填写菜单路由'; msgEl.classList.add('err'); return; + } + if (sortOrderValue !== '' && isNaN(sortOrder)) { + msgEl.textContent = '排序必须是数字'; msgEl.classList.add('err'); return; + } + fetch('/api/admin/column/' + cid, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: name, column_key: key, route_path: routePath, menu_type: menuType, sort_order: sortOrder }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editColumnModal').classList.remove('show'); + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + } else { + msgEl.textContent = res.error || '保存失败'; + msgEl.classList.add('err'); + } + }); + }; + + // ========== 分页 ========== + function renderPagination(elId, total, page, pageSize, onPage) { + var el = document.getElementById(elId); + if (!el) return; + var totalPages = Math.max(1, Math.ceil(total / pageSize)); + el.innerHTML = '共' + total + ' 条' + + '' + + '第' + page + ' / ' + totalPages + ' 页' + + ''; + el.querySelectorAll('[data-p]').forEach(function (b) { + if (!b.disabled) b.onclick = function () { onPage(parseInt(b.dataset.p, 10)); }; + }); + } + + // 初始化 + function loadAdminCurrentUser() { + fetch('/api/admin/current-user') + .then(function (r) { + if (r.status === 404) { + return fetch('/api/auth/check') + .then(function (fallbackResp) { return fallbackResp.json(); }) + .then(function (fallbackRes) { + if (fallbackRes && fallbackRes.logged_in) { + return { + success: true, + item: { + username: '当前用户', + role: '' + } + }; + } + return { success: false }; + }); + } + return r.json(); + }) + .then(function (res) { + var nameEl = document.getElementById('adminCurrentUsername'); + var roleEl = document.getElementById('adminCurrentUserRole'); + if (!res.success) { + nameEl.textContent = '未登录'; + roleEl.style.display = 'none'; + return; + } + var item = res.item || {}; + nameEl.textContent = item.username || '管理员'; + if (item.role) { + roleEl.textContent = item.role === 'super_admin' ? '超级管理员' : '管理员'; + roleEl.style.display = 'inline-block'; + } else { + roleEl.style.display = 'none'; + } + }) + .catch(function () { + fetch('/api/auth/check') + .then(function (r) { return r.json(); }) + .then(function (res) { + document.getElementById('adminCurrentUsername').textContent = res && res.logged_in ? '当前用户' : '未登录'; + document.getElementById('adminCurrentUserRole').style.display = 'none'; + }) + .catch(function () { + document.getElementById('adminCurrentUsername').textContent = '当前用户'; + document.getElementById('adminCurrentUserRole').style.display = 'none'; + }); + }); + } + + document.getElementById('btnAdminLogout').onclick = function () { + fetch('/api/admin/logout', { + method: 'POST', + headers: { 'X-Requested-With': 'XMLHttpRequest' } + }) + .then(function (r) { + if (r.status === 404) { + window.location.href = '/logout'; + return null; + } + return r.json(); + }) + .then(function (res) { + if (!res) return; + if (!res.success) { + alert(res.error || '退出失败'); + return; + } + window.location.href = res.redirect || '/login'; + }) + .catch(function () { + window.location.href = '/logout'; + }); + }; + + loadAdminCurrentUser(); + loadUserOptions(); + loadColumnsForPermission(); + loadShopManageGroups(); + loadAdminMenus(); + }) (); + \ No newline at end of file diff --git a/backend/web_source/_tmp_prefix.js b/backend/web_source/_tmp_prefix.js new file mode 100644 index 0000000..c578064 --- /dev/null +++ b/backend/web_source/_tmp_prefix.js @@ -0,0 +1,2000 @@ + + (function () { + // Tab 鍒囨崲 + var adminTabsEl = document.getElementById('adminTabs'); + if (adminTabsEl) adminTabsEl.innerHTML = ''; + var activeAdminTabName = ''; + var ADMIN_PANEL_MAP = { + 'users': 'panel-users', + 'columns': 'panel-columns', + 'dedupe-total-data': 'panel-dedupe-total-data', + 'shop-keys': 'panel-shop-keys', + 'shop-manage': 'panel-shop-manage', + 'skip-price-asin': 'panel-skip-price-asin', + 'history': 'panel-history', + 'version': 'panel-version' + }; + function runTabLoader(tabName) { + if (tabName === 'users') { loadUsers(1); loadColumnsForPermission(); } + else if (tabName === 'columns') loadColumns(); + else if (tabName === 'dedupe-total-data') loadDedupeTotalData(1); + else if (tabName === 'shop-keys') loadShopKeys(1); + else if (tabName === 'shop-manage') loadShopManage(1); + else if (tabName === 'skip-price-asin') loadSkipPriceAsin(1); + else if (tabName === 'history') loadHistory(1); + else if (tabName === 'version') loadVersions(); + } + function hideAllAdminPanels() { + document.querySelectorAll('.tab-panel').forEach(function (panel) { + panel.classList.remove('active'); + panel.style.display = 'none'; + }); + } + function getActiveAdminTabName() { + return activeAdminTabName; + } + function activateAdminTab(tabName) { + var panelId = ADMIN_PANEL_MAP[tabName]; + var panel = panelId ? document.getElementById(panelId) : null; + if (!panel) return; + activeAdminTabName = tabName; + document.querySelectorAll('#adminTabs .tab').forEach(function (tab) { + tab.classList.toggle('active', tab.dataset.tab === tabName); + }); + hideAllAdminPanels(); + panel.style.display = ''; + panel.classList.add('active'); + runTabLoader(tabName); + } + function renderAdminTabs(items) { + var knownItems = (items || []).filter(function (item) { + return !!ADMIN_PANEL_MAP[item.route_path]; + }); + if (!knownItems.length) { + activeAdminTabName = ''; + if (adminTabsEl) adminTabsEl.innerHTML = '
鏆傛棤鍙敤鑿滃崟
'; + hideAllAdminPanels(); + return; + } + if (adminTabsEl) { + adminTabsEl.innerHTML = knownItems.map(function (item) { + return '
' + (item.name || item.route_path) + '
'; + }).join(''); + } + document.querySelectorAll('#adminTabs .tab').forEach(function (tab) { + tab.onclick = function () { + activateAdminTab(tab.dataset.tab); + }; + }); + var fallbackTab = activeAdminTabName && knownItems.some(function (item) { return item.route_path === activeAdminTabName; }) + ? activeAdminTabName + : knownItems[0].route_path; + activateAdminTab(fallbackTab); + } + function loadAdminMenus(preferredTab) { + if (preferredTab) activeAdminTabName = preferredTab; + fetch('/api/admin/current-user/menus') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + if (adminTabsEl) adminTabsEl.innerHTML = '
鑿滃崟鍔犺浇澶辫触
'; + hideAllAdminPanels(); + return; + } + renderAdminTabs(res.items || []); + }) + .catch(function () { + if (adminTabsEl) adminTabsEl.innerHTML = '
鑿滃崟鍔犺浇澶辫触
'; + hideAllAdminPanels(); + }); + } + hideAllAdminPanels(); + + // ========== 鐢ㄦ埛绠$悊 ========== + var userPage = 1, userPageSize = 15; + var currentUserId = null; + var currentUserRole = 'admin'; + var currentUserUsername = ''; + var adminsList = []; + function roleLabel(role) { + if (role === 'super_admin') return '瓒呯骇绠$悊鍛?; + if (role === 'admin') return '绠$悊鍛?; + return '鏅€氳处鍙?; + } + function buildUserListQuery(page) { + var q = 'page=' + (page || 1) + '&page_size=' + userPageSize; + var kw = (document.getElementById('searchUsername').value || '').trim(); + if (kw) q += '&username=' + encodeURIComponent(kw); + var cby = document.getElementById('filterCreatedBy').value; + if (cby) q += '&created_by_id=' + encodeURIComponent(cby); + return q; + } + function loadUsers(page) { + userPage = page || 1; + fetch('/api/admin/users?' + buildUserListQuery(userPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('userListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + currentUserId = res.current_user_id || null; + currentUserRole = res.current_user_role || 'admin'; + currentUserUsername = (res.current_user_username || '').trim(); + adminsList = res.admins || []; + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤鐢ㄦ埛'; + } else { + tbody.innerHTML = items.map(function (u) { + return '' + u.id + '' + (u.username || '') + '' + + roleLabel(u.role || 'normal') + '' + (u.creator_username || '-') + '' + (u.created_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('userPagination', res.total, res.page, res.page_size, loadUsers); + bindUserActions(); + updateCreateFormByRole(); + updateUserFilterByRole(); + }) + .catch(function () { + document.getElementById('userListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + function updateUserFilterByRole() { + var grp = document.getElementById('filterCreatedByGroup'); + var sel = document.getElementById('filterCreatedBy'); + if (currentUserRole === 'super_admin') { + grp.style.display = 'block'; + var cur = sel.value; + sel.innerHTML = ''; + adminsList.forEach(function (a) { + var opt = document.createElement('option'); + opt.value = a.id; + opt.textContent = a.username; + sel.appendChild(opt); + }); + sel.value = cur || ''; + } else { + grp.style.display = 'none'; + } + } + + function updateDedupeTotalDataAccess() { + var tab = document.querySelector('.tab[data-tab="dedupe-total-data"]'); + var panel = document.getElementById('panel-dedupe-total-data'); + var canUse = currentUserRole === 'super_admin' || (currentUserRole === 'admin' && currentUserUsername === ''); + if (tab) tab.style.display = canUse ? '' : 'none'; + if (panel) panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab && tab.classList.contains('active')) { + tab.classList.remove('active'); + if (panel) panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function updateShopManageAccess() { + var tab = document.querySelector('.tab[data-tab="shop-manage"]'); + var panel = document.getElementById('panel-shop-manage'); + if (!tab || !panel) return; + var canUse = currentUserRole === 'super_admin' || + !!currentUserAdminPermissionKeys['admin_shop_manage'] || + !!currentUserAdminPermissionRoutes['shop-manage']; + tab.style.display = canUse ? '' : 'none'; + panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab.classList.contains('active')) { + tab.classList.remove('active'); + panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function loadCurrentUserAdminPermissions() { + currentUserAdminPermissionKeys = {}; + currentUserAdminPermissionRoutes = {}; + if (!currentUserId || currentUserRole === 'super_admin') { + updateShopManageAccess(); + return; + } + fetch('/api/admin/user/' + currentUserId + '/column-permissions?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + updateShopManageAccess(); + return; + } + (res.items || []).forEach(function (item) { + var columnKey = (item.column_key || '').trim(); + var routePath = (item.route_path || '').trim(); + if (columnKey) currentUserAdminPermissionKeys[columnKey] = true; + if (routePath) currentUserAdminPermissionRoutes[routePath] = true; + }); + updateShopManageAccess(); + }) + .catch(function () { + updateShopManageAccess(); + }); + } + function applyTabAccess(tabName, canUse) { + var tab = document.querySelector('.tab[data-tab="' + tabName + '"]'); + var panel = document.getElementById('panel-' + tabName); + if (tab) tab.style.display = canUse ? '' : 'none'; + if (panel) panel.style.display = canUse ? '' : 'none'; + if (!canUse && tab && tab.classList.contains('active')) { + tab.classList.remove('active'); + if (panel) panel.classList.remove('active'); + var usersTab = document.querySelector('.tab[data-tab="users"]'); + var usersPanel = document.getElementById('panel-users'); + if (usersTab) usersTab.classList.add('active'); + if (usersPanel) usersPanel.classList.add('active'); + } + } + function hasAdminTabAccess(tabName) { + var config = ADMIN_TAB_ACCESS_CONFIG[tabName]; + if (!config) return true; + if (currentUserRole === 'super_admin') return true; + if (config.superAdminOnly) return false; + return !!currentUserAdminPermissionKeys[config.columnKey] || + !!currentUserAdminPermissionRoutes[config.routePath]; + } + function refreshAdminTabAccess() { + Object.keys(ADMIN_TAB_ACCESS_CONFIG).forEach(function (tabName) { + applyTabAccess(tabName, hasAdminTabAccess(tabName)); + }); + } + function loadCurrentUserAdminPermissions() { + currentUserAdminPermissionKeys = {}; + currentUserAdminPermissionRoutes = {}; + if (!currentUserId || currentUserRole === 'super_admin') { + refreshAdminTabAccess(); + return; + } + fetch('/api/admin/user/' + currentUserId + '/column-permissions?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + refreshAdminTabAccess(); + return; + } + (res.items || []).forEach(function (item) { + var columnKey = (item.column_key || '').trim(); + var routePath = (item.route_path || '').trim(); + if (columnKey) currentUserAdminPermissionKeys[columnKey] = true; + if (routePath) currentUserAdminPermissionRoutes[routePath] = true; + }); + refreshAdminTabAccess(); + }) + .catch(function () { + refreshAdminTabAccess(); + }); + } + var allColumnsList = []; + function loadColumnsForPermission() { + fetch('/api/admin/columns?menu_type=admin') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) return; + allColumnsList = res.items || []; + renderColumnPermissionWrap('createColumnPermissionWrap'); + renderColumnPermissionWrap('editColumnPermissionWrap'); + var selCreate = document.getElementById('createColumnPermissionWrap'); + var selEdit = document.getElementById('editColumnPermissionWrap'); + if (selCreate && !selCreate._colCardsBound) { + selCreate._colCardsBound = true; + selCreate.onchange = function () { renderColumnCards('createColumnPermissionWrap'); }; + } + if (selEdit && !selEdit._colCardsBound) { + selEdit._colCardsBound = true; + selEdit.onchange = function () { renderColumnCards('editColumnPermissionWrap'); }; + } + }) + .catch(function () { }); + } + var columnCardsContainerMap = { createColumnPermissionWrap: 'createColumnCards', editColumnPermissionWrap: 'editColumnCards' }; + function renderColumnCards(selectId) { + var sel = document.getElementById(selectId); + var cardsId = columnCardsContainerMap[selectId]; + var cardsEl = cardsId ? document.getElementById(cardsId) : null; + if (!sel || sel.tagName !== 'SELECT' || !cardsEl) return; + cardsEl.innerHTML = ''; + for (var i = 0; i < sel.options.length; i++) { + var opt = sel.options[i]; + if (opt.disabled || !opt.selected) continue; + var card = document.createElement('span'); + card.className = 'column-permission-card'; + card.textContent = opt.textContent; + var btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'col-card-remove'; + btn.setAttribute('aria-label', '绉婚櫎'); + btn.textContent = '脳'; + (function (option, seldId) { + btn.onclick = function () { + option.selected = false; + renderColumnCards(seldId); + }; + })(opt, selectId); + card.appendChild(btn); + cardsEl.appendChild(card); + } + } + function renderColumnPermissionWrap(wrapId) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return; + sel.innerHTML = ''; + allColumnsList.forEach(function (c) { + var opt = document.createElement('option'); + opt.value = c.id; + opt.textContent = c.name + ' (' + c.column_key + ')'; + sel.appendChild(opt); + }); + if (allColumnsList.length === 0) { + var opt = document.createElement('option'); + opt.disabled = true; + opt.textContent = '鏆傛棤鑿滃崟锛岃鍏堝湪鈥滄爮鐩潈闄愰厤缃€濅腑鏂板鑿滃崟'; + sel.appendChild(opt); + } + renderColumnCards(wrapId); + } + function getSelectedColumnIds(wrapId) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return []; + var ids = []; + for (var i = 0; i < sel.options.length; i++) { + if (sel.options[i].selected) { + var v = parseInt(sel.options[i].value, 10); + if (!isNaN(v)) ids.push(v); + } + } + return ids; + } + function setColumnPermissionCheckboxes(wrapId, columnIds) { + var sel = document.getElementById(wrapId); + if (!sel || sel.tagName !== 'SELECT') return; + var set = {}; + (columnIds || []).forEach(function (id) { set[id] = true; }); + for (var i = 0; i < sel.options.length; i++) { + var opt = sel.options[i]; + if (opt.disabled) continue; + opt.selected = set[parseInt(opt.value, 10)] || false; + } + renderColumnCards(wrapId); + } + function updateCreateFormByRole() { + var roleSel = document.getElementById('createRole'); + var optAdmin = document.getElementById('optAdmin'); + var formCreatedBy = document.getElementById('formGroupCreatedBy'); + var selCreatedBy = document.getElementById('createCreatedBy'); + if (currentUserRole === 'super_admin') { + if (optAdmin) optAdmin.style.display = ''; + formCreatedBy.style.display = (roleSel.value === 'normal') ? 'block' : 'none'; + selCreatedBy.innerHTML = ''; + (res.items || []).forEach(function (u) { + var opt = document.createElement('option'); + opt.value = u.id; + opt.textContent = u.username + ' (' + roleLabel(u.role || 'normal') + ')'; + sel.appendChild(opt); + }); + sel.value = cur || ''; + }); + } + var shopManageGroupUsers = []; + function refreshShopManageGroupUserSelect(selectedUserId) { + var sel = document.getElementById('shopManageGroupUserSelect'); + if (!sel) return; + var opts = ['']; + shopManageGroupUsers.forEach(function (u) { + opts.push(''); + }); + sel.innerHTML = opts.join(''); + if (selectedUserId != null && selectedUserId !== '') { + sel.value = String(selectedUserId); + } + syncShopManageGroupNameWithUser(); + } + function syncShopManageGroupNameWithUser() { + var sel = document.getElementById('shopManageGroupUserSelect'); + var input = document.getElementById('shopManageGroupInput'); + if (!sel || !input) return; + var selectedUser = null; + shopManageGroupUsers.some(function (u) { + if (String(u.id) === String(sel.value || '')) { + selectedUser = u; + return true; + } + return false; + }); + input.value = selectedUser ? (selectedUser.username || '') : ''; + } + function loadUserOptions() { + return fetch('/api/admin/users?page=1&page_size=999') + .then(function (r) { return r.json(); }) + .then(function (res) { + var items = res.items || []; + shopManageGroupUsers = items.map(function (u) { + return { id: u.id, username: u.username || '', role: u.role || 'normal' }; + }); + refreshShopManageGroupUserSelect(document.getElementById('shopManageGroupUserSelect') ? document.getElementById('shopManageGroupUserSelect').value : ''); + var sel = document.getElementById('filterUser'); + var cur = sel.value; + sel.innerHTML = ''; + items.forEach(function (u) { + var opt = document.createElement('option'); + opt.value = u.id; + opt.textContent = u.username + ' (' + roleLabel(u.role || 'normal') + ')'; + sel.appendChild(opt); + }); + sel.value = cur || ''; + }); + } + document.getElementById('btnFilterHistory').onclick = function () { loadHistory(1); }; + + // ========== 鏁版嵁鍘婚噸鎬绘暟鎹?========== + var dedupeTotalDataPage = 1, dedupeTotalDataPageSize = 15; + function buildDedupeTotalDataQuery(page) { + var q = 'page=' + (page || 1) + '&page_size=' + dedupeTotalDataPageSize; + var keyword = (document.getElementById('searchDedupeTotalData').value || '').trim(); + if (keyword) q += '&keyword=' + encodeURIComponent(keyword); + return q; + } + function loadDedupeTotalData(page) { + dedupeTotalDataPage = page || 1; + fetch('/api/admin/dedupe-total-data?' + buildDedupeTotalDataQuery(dedupeTotalDataPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('dedupeTotalDataListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤鎬绘暟鎹?/td>'; + } else { + tbody.innerHTML = items.map(function (item) { + return '' + item.id + '' + (item.data_value || '') + '' + (item.created_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('dedupeTotalDataPagination', res.total, res.page, res.page_size, loadDedupeTotalData); + bindDedupeTotalDataActions(); + }) + .catch(function () { + document.getElementById('dedupeTotalDataListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + function bindDedupeTotalDataActions() { + document.querySelectorAll('[data-dedupe-total-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('editDedupeTotalDataId').value = btn.dataset.dedupeTotalEdit || ''; + document.getElementById('editDedupeTotalDataValue').value = (btn.dataset.value || '').replace(/"/g, '"'); + document.getElementById('msgEditDedupeTotalData').textContent = ''; + document.getElementById('msgEditDedupeTotalData').className = 'msg'; + document.getElementById('editDedupeTotalDataModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-dedupe-total-delete]').forEach(function (btn) { + btn.onclick = function () { + var value = (btn.dataset.value || '').replace(/"/g, '"'); + if (!confirm('纭畾鍒犻櫎鎬绘暟鎹€? + value + '鈥濆悧锛?)) return; + fetch('/api/admin/dedupe-total-data/' + btn.dataset.dedupeTotalDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadDedupeTotalData(dedupeTotalDataPage); } + else { alert(res.error || '鍒犻櫎澶辫触'); } + }); + }; + }); + } + document.getElementById('btnSearchDedupeTotalData').onclick = function () { loadDedupeTotalData(1); }; + var dedupeImportPollTimer = null; + var dedupeDeleteImportPollTimer = null; + function stopDedupeImportProgress() { + if (dedupeImportPollTimer) { + clearInterval(dedupeImportPollTimer); + dedupeImportPollTimer = null; + } + } + function stopDedupeDeleteImportProgress() { + if (dedupeDeleteImportPollTimer) { + clearInterval(dedupeDeleteImportPollTimer); + dedupeDeleteImportPollTimer = null; + } + } + function setDedupeImportProgress(percent, text) { + var wrap = document.getElementById('dedupeTotalDataProgressWrap'); + var fill = document.getElementById('dedupeTotalDataProgressFill'); + var textEl = document.getElementById('dedupeTotalDataProgressText'); + wrap.style.display = 'block'; + fill.style.width = Math.max(0, Math.min(100, percent || 0)) + '%'; + textEl.textContent = text || ''; + } + function setDedupeDeleteImportProgress(percent, text) { + var wrap = document.getElementById('dedupeTotalDataDeleteProgressWrap'); + var fill = document.getElementById('dedupeTotalDataDeleteProgressFill'); + var textEl = document.getElementById('dedupeTotalDataDeleteProgressText'); + wrap.style.display = 'block'; + fill.style.width = Math.max(0, Math.min(100, percent || 0)) + '%'; + textEl.textContent = text || ''; + } + function pollDedupeImport(importId) { + stopDedupeImportProgress(); + function tick() { + fetch('/api/admin/dedupe-total-data/import/' + encodeURIComponent(importId)) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = res.error || '鏌ヨ瀵煎叆杩涘害澶辫触'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + return; + } + var progress = res.progress || {}; + var totalRows = progress.total_rows || 0; + var processedRows = progress.processed_rows || 0; + var percent = totalRows > 0 ? Math.round(processedRows * 100 / totalRows) : 0; + setDedupeImportProgress(percent, '澶勭悊涓細宸插鐞?' + processedRows + ' / ' + totalRows + '锛屾柊澧?' + (progress.inserted_count || 0) + '锛岃烦杩?' + (progress.skipped_count || 0)); + if (progress.status === 'success') { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = '瀵煎叆鎴愬姛锛氭€昏鏁?' + (progress.total_rows || 0) + '锛孉SIN 鏁伴噺 ' + (progress.asin_count || 0) + '锛屾柊澧?' + (progress.inserted_count || 0) + '锛岃烦杩?' + (progress.skipped_count || 0); + document.getElementById('msgDedupeTotalData').className = 'msg ok'; + loadDedupeTotalData(1); + } else if (progress.status === 'failed') { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = progress.error_message || '瀵煎叆澶辫触'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + } + }) + .catch(function () { + stopDedupeImportProgress(); + document.getElementById('msgDedupeTotalData').textContent = '鏌ヨ瀵煎叆杩涘害澶辫触'; + document.getElementById('msgDedupeTotalData').className = 'msg err'; + }); + } + tick(); + dedupeImportPollTimer = setInterval(tick, 1000); + } + function pollDedupeDeleteImport(importId) { + stopDedupeDeleteImportProgress(); + function tick() { + fetch('/api/admin/dedupe-total-data/delete-import/' + encodeURIComponent(importId)) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = res.error || '鏌ヨ鍒犻櫎杩涘害澶辫触'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + return; + } + var progress = res.progress || {}; + var totalRows = progress.total_rows || 0; + var processedRows = progress.processed_rows || 0; + var percent = totalRows > 0 ? Math.round(processedRows * 100 / totalRows) : 0; + setDedupeDeleteImportProgress(percent, '澶勭悊涓細宸插鐞?' + processedRows + ' / ' + totalRows + '锛屽垹闄?' + (progress.deleted_count || 0) + '锛岃烦杩?' + (progress.skipped_count || 0)); + if (progress.status === 'success') { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = '鍒犻櫎鎴愬姛锛氭€昏鏁?' + (progress.total_rows || 0) + '锛孉SIN 鏁伴噺 ' + (progress.asin_count || 0) + '锛屽垹闄?' + (progress.deleted_count || 0) + '锛岃烦杩?' + (progress.skipped_count || 0); + document.getElementById('msgDeleteDedupeTotalData').className = 'msg ok'; + loadDedupeTotalData(1); + } else if (progress.status === 'failed') { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = progress.error_message || '鍒犻櫎澶辫触'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + } + }) + .catch(function () { + stopDedupeDeleteImportProgress(); + document.getElementById('msgDeleteDedupeTotalData').textContent = '鏌ヨ鍒犻櫎杩涘害澶辫触'; + document.getElementById('msgDeleteDedupeTotalData').className = 'msg err'; + }); + } + tick(); + dedupeDeleteImportPollTimer = setInterval(tick, 1000); + } + + document.getElementById('btnAddDedupeTotalData').onclick = function () { + var fileInput = document.getElementById('dedupeTotalDataFile'); + var msgEl = document.getElementById('msgDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + stopDedupeImportProgress(); + document.getElementById('dedupeTotalDataProgressWrap').style.display = 'none'; + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '璇烽€夋嫨 Excel 鏂囦欢'; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + var lowerName = (file.name || '').toLowerCase(); + if (!(lowerName.endsWith('.xlsx') || lowerName.endsWith('.xls'))) { + msgEl.textContent = '浠呮敮鎸?.xlsx 鎴?.xls 鏂囦欢'; + msgEl.classList.add('err'); + return; + } + var formData = new FormData(); + formData.append('file', file); + var xhr = new XMLHttpRequest(); + xhr.open('POST', '/api/admin/dedupe-total-data/import', true); + xhr.upload.onprogress = function (event) { + if (event.lengthComputable) { + var percent = Math.round(event.loaded * 100 / event.total); + setDedupeImportProgress(percent, '涓婁紶涓細' + percent + '%'); + } + }; + xhr.onreadystatechange = function () { + if (xhr.readyState !== 4) return; + if (xhr.status < 200 || xhr.status >= 300) { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + return; + } + var res; + try { res = JSON.parse(xhr.responseText || '{}'); } catch (e) { res = { success: false, error: '杩斿洖鏍煎紡閿欒' }; } + if (!res.success) { + msgEl.textContent = res.error || '瀵煎叆澶辫触'; + msgEl.className = 'msg err'; + return; + } + setDedupeImportProgress(100, '涓婁紶瀹屾垚锛屽悗绔鐞嗕腑...'); + pollDedupeImport(res.import_id); + fileInput.value = ''; + }; + xhr.onerror = function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }; + xhr.send(formData); + }; + document.getElementById('btnDeleteImportDedupeTotalData').onclick = function () { + var fileInput = document.getElementById('dedupeTotalDataDeleteFile'); + var msgEl = document.getElementById('msgDeleteDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + stopDedupeDeleteImportProgress(); + document.getElementById('dedupeTotalDataDeleteProgressWrap').style.display = 'none'; + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '璇烽€夋嫨 Excel 鏂囦欢'; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + var lowerName = (file.name || '').toLowerCase(); + if (!(lowerName.endsWith('.xlsx') || lowerName.endsWith('.xls'))) { + msgEl.textContent = '浠呮敮鎸?.xlsx 鎴?.xls 鏂囦欢'; + msgEl.classList.add('err'); + return; + } + if (!confirm('纭畾鎸?Excel 涓殑 ASIN 鎵归噺鍒犻櫎鍖归厤鐨勬€绘暟鎹悧锛?)) { + return; + } + var formData = new FormData(); + formData.append('file', file); + var xhr = new XMLHttpRequest(); + xhr.open('POST', '/api/admin/dedupe-total-data/delete-import', true); + xhr.upload.onprogress = function (event) { + if (event.lengthComputable) { + var percent = Math.round(event.loaded * 100 / event.total); + setDedupeDeleteImportProgress(percent, '涓婁紶涓細' + percent + '%'); + } + }; + xhr.onreadystatechange = function () { + if (xhr.readyState !== 4) return; + if (xhr.status < 200 || xhr.status >= 300) { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + return; + } + var res; + try { res = JSON.parse(xhr.responseText || '{}'); } catch (e) { res = { success: false, error: '杩斿洖鏍煎紡閿欒' }; } + if (!res.success) { + msgEl.textContent = res.error || '鍒犻櫎澶辫触'; + msgEl.className = 'msg err'; + return; + } + setDedupeDeleteImportProgress(100, '涓婁紶瀹屾垚锛屽悗绔鐞嗕腑...'); + pollDedupeDeleteImport(res.import_id); + fileInput.value = ''; + }; + xhr.onerror = function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }; + xhr.send(formData); + }; + document.getElementById('btnSaveDedupeTotalData').onclick = function () { + var itemId = document.getElementById('editDedupeTotalDataId').value; + var value = (document.getElementById('editDedupeTotalDataValue').value || '').trim(); + var msgEl = document.getElementById('msgEditDedupeTotalData'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!value) { + msgEl.textContent = '璇峰~鍐欐€绘暟鎹€?; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/dedupe-total-data/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ data_value: value }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editDedupeTotalDataModal').classList.remove('show'); + loadDedupeTotalData(dedupeTotalDataPage); + } else { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.classList.add('err'); + } + }); + }; + document.getElementById('btnCloseEditDedupeTotalData').onclick = function () { + document.getElementById('editDedupeTotalDataModal').classList.remove('show'); + }; + + // ========== 搴楅摵瀵嗛挜绠$悊 ========== + var shopKeyPage = 1, shopKeyPageSize = 15; + function buildShopKeyQuery(page) { + return 'page=' + (page || 1) + '&page_size=' + shopKeyPageSize; + } + function loadShopKeys(page) { + shopKeyPage = page || 1; + fetch('/api/admin/shop-keys?' + buildShopKeyQuery(shopKeyPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('shopKeyListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤搴楅摵瀵嗛挜'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (shopKeyPage - 1) * shopKeyPageSize + index + 1; + return '' + rowNo + '' + (item.ziniao_account_name || '') + '' + (item.ziniao_token || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('shopKeyPagination', res.total, res.page, res.page_size, loadShopKeys); + bindShopKeyActions(); + }) + .catch(function () { + document.getElementById('shopKeyListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + function bindShopKeyActions() { + document.querySelectorAll('[data-shop-key-edit]').forEach(function (btn) { + btn.onclick = function () { + var item = {}; + try { item = JSON.parse((btn.dataset.shopKey || '').replace(/"/g, '"')); } catch (e) { item = {}; } + document.getElementById('editShopKeyId').value = item.id || ''; + document.getElementById('editShopKeyZiniaoAccountName').value = item.ziniao_account_name || ''; + document.getElementById('editShopKeyZiniaoToken').value = item.ziniao_token || ''; + document.getElementById('msgEditShopKey').textContent = ''; + document.getElementById('msgEditShopKey').className = 'msg'; + document.getElementById('editShopKeyModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-shop-key-delete]').forEach(function (btn) { + btn.onclick = function () { + var name = (btn.dataset.ziniaoAccountName || '').replace(/"/g, '"'); + if (!confirm('纭畾鍒犻櫎搴楅摵瀵嗛挜鈥? + name + '鈥濆悧锛?)) return; + fetch('/api/admin/shop-key/' + btn.dataset.shopKeyDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadShopKeys(shopKeyPage); } + else { alert(res.error || '鍒犻櫎澶辫触'); } + }); + }; + }); + } + document.getElementById('btnCreateShopKey').onclick = function () { + var ziniaoAccountName = (document.getElementById('shopKeyZiniaoAccountName').value || '').trim(); + var ziniaoToken = (document.getElementById('shopKeyZiniaoToken').value || '').trim(); + var msgEl = document.getElementById('msgShopKey'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!ziniaoAccountName || !ziniaoToken) { + msgEl.textContent = '璇峰畬鏁村~鍐欑传楦熻处鍙峰悕绉般€佺传楦熶护鐗?; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-key', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ziniao_account_name: ziniaoAccountName, + ziniao_token: ziniaoToken + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('shopKeyZiniaoAccountName').value = ''; + document.getElementById('shopKeyZiniaoToken').value = ''; + msgEl.textContent = res.msg || '鍒涘缓鎴愬姛'; + msgEl.className = 'msg ok'; + loadShopKeys(1); + } else { + msgEl.textContent = res.error || '鍒涘缓澶辫触'; + msgEl.className = 'msg err'; + } + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }); + }; + document.getElementById('btnSaveShopKey').onclick = function () { + var itemId = document.getElementById('editShopKeyId').value; + var ziniaoAccountName = (document.getElementById('editShopKeyZiniaoAccountName').value || '').trim(); + var ziniaoToken = (document.getElementById('editShopKeyZiniaoToken').value || '').trim(); + var msgEl = document.getElementById('msgEditShopKey'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!ziniaoAccountName || !ziniaoToken) { + msgEl.textContent = '璇峰畬鏁村~鍐欑传楦熻处鍙峰悕绉般€佺传楦熶护鐗?; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-key/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ziniao_account_name: ziniaoAccountName, + ziniao_token: ziniaoToken + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editShopKeyModal').classList.remove('show'); + loadShopKeys(shopKeyPage); + } else { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.classList.add('err'); + }); + }; + document.getElementById('btnCloseEditShopKey').onclick = function () { + document.getElementById('editShopKeyModal').classList.remove('show'); + }; + + // ========== 搴楅摵绠$悊 ========== + var shopManagePage = 1, shopManagePageSize = 15; + var shopManageGroups = []; + + function buildShopManageQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + shopManagePageSize; + var groupId = (document.getElementById('shopManageFilterGroupId').value || '').trim(); + var shopName = (document.getElementById('shopManageFilterShopName').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + return query; + } + + function refreshShopGroupSelects(selectedCreateId, selectedEditId) { + var createSel = document.getElementById('shopManageGroupSelect'); + var editSel = document.getElementById('editShopManageGroupSelect'); + var filterSel = document.getElementById('shopManageFilterGroupId'); + var skipCreateSel = document.getElementById('skipPriceAsinGroupSelect'); + var skipFilterSel = document.getElementById('skipPriceAsinFilterGroupId'); + var chooseSkipShopSel = document.getElementById('chooseSkipPriceAsinShopGroupId'); + var selectedFilterId = filterSel ? filterSel.value : ''; + var selectedSkipCreateId = skipCreateSel ? skipCreateSel.value : ''; + var selectedSkipFilterId = skipFilterSel ? skipFilterSel.value : ''; + var selectedChooseSkipShopId = chooseSkipShopSel ? chooseSkipShopSel.value : ''; + var createOpts = ['']; + var filterOpts = ['']; + shopManageGroups.forEach(function (g) { + var option = ''; + createOpts.push(option); + filterOpts.push(option); + }); + createSel.innerHTML = createOpts.join(''); + editSel.innerHTML = createOpts.join(''); + if (skipCreateSel) skipCreateSel.innerHTML = createOpts.join(''); + if (filterSel) filterSel.innerHTML = filterOpts.join(''); + if (skipFilterSel) skipFilterSel.innerHTML = filterOpts.join(''); + if (chooseSkipShopSel) chooseSkipShopSel.innerHTML = filterOpts.join(''); + if (selectedCreateId != null) createSel.value = String(selectedCreateId); + if (selectedEditId != null) editSel.value = String(selectedEditId); + if (filterSel && selectedFilterId) filterSel.value = selectedFilterId; + if (skipCreateSel && selectedSkipCreateId) skipCreateSel.value = selectedSkipCreateId; + if (skipFilterSel && selectedSkipFilterId) skipFilterSel.value = selectedSkipFilterId; + if (chooseSkipShopSel && selectedChooseSkipShopId) chooseSkipShopSel.value = selectedChooseSkipShopId; + } + + function loadShopManageGroups(selectedCreateId, selectedEditId) { + return fetch('/api/admin/shop-manage-groups') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) throw new Error(res.error || '鍔犺浇鍒嗙粍澶辫触'); + shopManageGroups = res.items || []; + refreshShopGroupSelects(selectedCreateId, selectedEditId); + return shopManageGroups; + }) + .catch(function () { + shopManageGroups = []; + refreshShopGroupSelects(); + return []; + }); + } + + function openShopManageGroupModal() { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + document.getElementById('msgShopManageGroup').textContent = ''; + document.getElementById('msgShopManageGroup').className = 'msg'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + document.getElementById('shopManageGroupModal').classList.add('show'); + }); + } + + function renderShopManageGroupRows() { + var tbody = document.getElementById('shopManageGroupListBody'); + if (!shopManageGroups.length) { + tbody.innerHTML = '鏆傛棤鍒嗙粍'; + return; + } + tbody.innerHTML = shopManageGroups.map(function (item, index) { + return '' + (index + 1) + '' + (item.group_name || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + + document.querySelectorAll('[data-shop-group-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('shopManageGroupEditId').value = btn.dataset.shopGroupEdit; + document.getElementById('shopManageGroupInput').value = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + }; + }); + + document.querySelectorAll('[data-shop-group-delete]').forEach(function (btn) { + btn.onclick = function () { + var gid = btn.dataset.shopGroupDelete; + var gname = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + if (!confirm('纭畾鍒犻櫎鍒嗙粍鈥? + gname + '鈥濆悧锛?)) return; + fetch('/api/admin/shop-manage-group/' + gid, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + alert(res.error || '鍒犻櫎澶辫触'); + return; + } + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }); + }; + }); + } + + function loadShopManage(page) { + shopManagePage = page || 1; + fetch('/api/admin/shop-manages?' + buildShopManageQuery(shopManagePage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('shopManageListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤搴楅摵'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (shopManagePage - 1) * shopManagePageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + (item.mall_name || '') + '' + (item.account || '') + '' + (item.password || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + } + renderPagination('shopManagePagination', res.total, res.page, res.page_size, loadShopManage); + bindShopManageActions(); + }) + .catch(function () { + document.getElementById('shopManageListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + + function bindShopManageActions() { + document.querySelectorAll('[data-shop-manage-edit]').forEach(function (btn) { + btn.onclick = function () { + var item = {}; + try { item = JSON.parse((btn.dataset.shopManage || '').replace(/"/g, '"')); } catch (e) { item = {}; } + document.getElementById('editShopManageId').value = item.id || ''; + document.getElementById('editShopManageShopName').value = item.shop_name || ''; + document.getElementById('editShopManageMallName').value = item.mall_name || ''; + document.getElementById('editShopManageAccount').value = item.account || ''; + document.getElementById('editShopManagePassword').value = item.password || ''; + document.getElementById('msgEditShopManage').textContent = ''; + document.getElementById('msgEditShopManage').className = 'msg'; + loadShopManageGroups(null, item.group_id).then(function () { + document.getElementById('editShopManageModal').classList.add('show'); + }); + }; + }); + document.querySelectorAll('[data-shop-manage-delete]').forEach(function (btn) { + btn.onclick = function () { + var name = (btn.dataset.shopManageName || '').replace(/"/g, '"'); + if (!confirm('纭畾鍒犻櫎搴楅摵鈥? + name + '鈥濆悧锛?)) return; + fetch('/api/admin/shop-manage/' + btn.dataset.shopManageDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadShopManage(shopManagePage); } + else { alert(res.error || '鍒犻櫎澶辫触'); } + }); + }; + }); + } + + document.getElementById('btnManageShopGroups').onclick = openShopManageGroupModal; + document.getElementById('btnManageShopGroupsFromEdit').onclick = openShopManageGroupModal; + document.getElementById('btnSearchShopManage').onclick = function () { + loadShopManage(1); + }; + document.getElementById('shopManageFilterShopName').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadShopManage(1); + } + }); + document.getElementById('btnCloseShopManageGroupModal').onclick = function () { + document.getElementById('shopManageGroupModal').classList.remove('show'); + }; + document.getElementById('btnCancelShopManageGroupEdit').onclick = function () { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + }; + document.getElementById('btnSaveShopManageGroup').onclick = function () { + var editId = (document.getElementById('shopManageGroupEditId').value || '').trim(); + var groupName = (document.getElementById('shopManageGroupInput').value || '').trim(); + var msgEl = document.getElementById('msgShopManageGroup'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupName) { + msgEl.textContent = '璇疯緭鍏ュ垎缁勫悕绉?; + msgEl.className = 'msg err'; + return; + } + var method = editId ? 'PUT' : 'POST'; + var url = editId ? ('/api/admin/shop-manage-group/' + editId) : '/api/admin/shop-manage-group'; + fetch(url, { + method: method, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_name: groupName }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.className = 'msg err'; + return; + } + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + msgEl.textContent = res.msg || '淇濆瓨鎴愬姛'; + msgEl.className = 'msg ok'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }); + }; + + function refreshShopGroupSelects(selectedCreateId, selectedEditId) { + var createSel = document.getElementById('shopManageGroupSelect'); + var editSel = document.getElementById('editShopManageGroupSelect'); + var filterSel = document.getElementById('shopManageFilterGroupId'); + var skipCreateSel = document.getElementById('skipPriceAsinGroupSelect'); + var skipFilterSel = document.getElementById('skipPriceAsinFilterGroupId'); + var chooseSkipShopSel = document.getElementById('chooseSkipPriceAsinShopGroupId'); + var selectedFilterId = filterSel ? filterSel.value : ''; + var selectedSkipCreateId = skipCreateSel ? skipCreateSel.value : ''; + var selectedSkipFilterId = skipFilterSel ? skipFilterSel.value : ''; + var selectedChooseSkipShopId = chooseSkipShopSel ? chooseSkipShopSel.value : ''; + var createOpts = ['']; + var filterOpts = ['']; + shopManageGroups.forEach(function (g) { + var option = ''; + createOpts.push(option); + filterOpts.push(option); + }); + createSel.innerHTML = createOpts.join(''); + editSel.innerHTML = createOpts.join(''); + if (skipCreateSel) skipCreateSel.innerHTML = createOpts.join(''); + if (filterSel) filterSel.innerHTML = filterOpts.join(''); + if (skipFilterSel) skipFilterSel.innerHTML = filterOpts.join(''); + if (chooseSkipShopSel) chooseSkipShopSel.innerHTML = filterOpts.join(''); + if (selectedCreateId != null) createSel.value = String(selectedCreateId); + if (selectedEditId != null) editSel.value = String(selectedEditId); + if (filterSel && selectedFilterId) filterSel.value = selectedFilterId; + if (skipCreateSel && selectedSkipCreateId) skipCreateSel.value = selectedSkipCreateId; + if (skipFilterSel && selectedSkipFilterId) skipFilterSel.value = selectedSkipFilterId; + if (chooseSkipShopSel && selectedChooseSkipShopId) chooseSkipShopSel.value = selectedChooseSkipShopId; + } + + function loadShopManageGroups(selectedCreateId, selectedEditId) { + return fetch('/api/admin/shop-manage-groups') + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) throw new Error(res.error || '鍔犺浇鍒嗙粍澶辫触'); + shopManageGroups = res.items || []; + refreshShopGroupSelects(selectedCreateId, selectedEditId); + return shopManageGroups; + }) + .catch(function () { + shopManageGroups = []; + refreshShopGroupSelects(); + return []; + }); + } + + function resetShopManageGroupForm() { + document.getElementById('shopManageGroupEditId').value = ''; + document.getElementById('shopManageGroupInput').value = ''; + document.getElementById('msgShopManageGroup').textContent = ''; + document.getElementById('msgShopManageGroup').className = 'msg'; + refreshShopManageGroupUserSelect(''); + } + + function openShopManageGroupModal() { + resetShopManageGroupForm(); + loadUserOptions() + .then(function () { return loadShopManageGroups(); }) + .then(function () { + renderShopManageGroupRows(); + document.getElementById('shopManageGroupModal').classList.add('show'); + }); + } + + function renderShopManageGroupRows() { + var tbody = document.getElementById('shopManageGroupListBody'); + if (!shopManageGroups.length) { + tbody.innerHTML = '鏆傛棤鍒嗙粍'; + return; + } + tbody.innerHTML = shopManageGroups.map(function (item, index) { + return '' + (index + 1) + '' + (item.group_name || '') + '' + (item.username || '') + '' + (item.created_at || '') + '' + (item.updated_at || '') + '' + + ' ' + + '' + + ''; + }).join(''); + + document.querySelectorAll('[data-shop-group-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('shopManageGroupEditId').value = btn.dataset.shopGroupEdit; + refreshShopManageGroupUserSelect(btn.dataset.shopGroupUserId || ''); + }; + }); + + document.querySelectorAll('[data-shop-group-delete]').forEach(function (btn) { + btn.onclick = function () { + var gid = btn.dataset.shopGroupDelete; + var gname = (btn.dataset.shopGroupName || '').replace(/"/g, '"'); + if (!confirm('纭畾鍒犻櫎鍒嗙粍鈥? + gname + '鈥濆悧锛?)) return; + fetch('/api/admin/shop-manage-group/' + gid, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + alert(res.error || '鍒犻櫎澶辫触'); + return; + } + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }); + }; + }); + } + + document.getElementById('shopManageGroupUserSelect').onchange = syncShopManageGroupNameWithUser; + document.getElementById('btnManageShopGroups').onclick = openShopManageGroupModal; + document.getElementById('btnManageShopGroupsFromEdit').onclick = openShopManageGroupModal; + document.getElementById('btnManageSkipPriceAsinGroups').onclick = openShopManageGroupModal; + document.getElementById('btnCloseShopManageGroupModal').onclick = function () { + document.getElementById('shopManageGroupModal').classList.remove('show'); + }; + document.getElementById('btnCancelShopManageGroupEdit').onclick = resetShopManageGroupForm; + document.getElementById('btnSaveShopManageGroup').onclick = function () { + var editId = (document.getElementById('shopManageGroupEditId').value || '').trim(); + var groupName = (document.getElementById('shopManageGroupInput').value || '').trim(); + var userId = (document.getElementById('shopManageGroupUserSelect').value || '').trim(); + var msgEl = document.getElementById('msgShopManageGroup'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!userId || !groupName) { + msgEl.textContent = '璇烽€夋嫨鍏宠仈鐢ㄦ埛'; + msgEl.className = 'msg err'; + return; + } + var method = editId ? 'PUT' : 'POST'; + var url = editId ? ('/api/admin/shop-manage-group/' + editId) : '/api/admin/shop-manage-group'; + fetch(url, { + method: method, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_name: groupName, user_id: Number(userId) }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.className = 'msg err'; + return; + } + resetShopManageGroupForm(); + msgEl.textContent = res.msg || '淇濆瓨鎴愬姛'; + msgEl.className = 'msg ok'; + loadShopManageGroups().then(function () { + renderShopManageGroupRows(); + loadShopManage(shopManagePage); + loadSkipPriceAsin(skipPriceAsinPage); + }); + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }); + }; + + document.getElementById('btnCreateShopManage').onclick = function () { + var groupId = (document.getElementById('shopManageGroupSelect').value || '').trim(); + var shopName = (document.getElementById('shopManageShopName').value || '').trim(); + var mallName = (document.getElementById('shopManageMallName').value || '').trim(); + var account = (document.getElementById('shopManageAccount').value || '').trim(); + var password = (document.getElementById('shopManagePassword').value || '').trim(); + var msgEl = document.getElementById('msgShopManage'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !mallName || !account || !password) { + msgEl.textContent = '璇峰畬鏁村~鍐欏垎缁勩€佸簵閾哄悕銆佸簵閾哄晢鍩庡悕銆佽处鍙枫€佸瘑鐮?; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-manage', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_id: Number(groupId), shop_name: shopName, mall_name: mallName, account: account, password: password }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('shopManageGroupSelect').value = ''; + document.getElementById('shopManageShopName').value = ''; + document.getElementById('shopManageMallName').value = ''; + document.getElementById('shopManageAccount').value = ''; + document.getElementById('shopManagePassword').value = ''; + msgEl.textContent = res.msg || '鍒涘缓鎴愬姛'; + msgEl.className = 'msg ok'; + loadShopManage(1); + } else { + msgEl.textContent = res.error || '鍒涘缓澶辫触'; + msgEl.className = 'msg err'; + } + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }); + }; + + document.getElementById('btnSaveShopManage').onclick = function () { + var itemId = document.getElementById('editShopManageId').value; + var groupId = (document.getElementById('editShopManageGroupSelect').value || '').trim(); + var shopName = (document.getElementById('editShopManageShopName').value || '').trim(); + var mallName = (document.getElementById('editShopManageMallName').value || '').trim(); + var account = (document.getElementById('editShopManageAccount').value || '').trim(); + var password = (document.getElementById('editShopManagePassword').value || '').trim(); + var msgEl = document.getElementById('msgEditShopManage'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !mallName || !account || !password) { + msgEl.textContent = '璇峰畬鏁村~鍐欏垎缁勩€佸簵閾哄悕銆佸簵閾哄晢鍩庡悕銆佽处鍙枫€佸瘑鐮?; + msgEl.classList.add('err'); + return; + } + fetch('/api/admin/shop-manage/' + itemId, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ group_id: Number(groupId), shop_name: shopName, mall_name: mallName, account: account, password: password }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + document.getElementById('editShopManageModal').classList.remove('show'); + loadShopManage(shopManagePage); + } else { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.classList.add('err'); + }); + }; + document.getElementById('btnCloseEditShopManage').onclick = function () { + document.getElementById('editShopManageModal').classList.remove('show'); + }; + + // ========== 鐗堟湰绠$悊 ========== + // ========== 璺宠繃璺熶环 ASIN ========== + var skipPriceAsinPage = 1, skipPriceAsinPageSize = 15; + var chooseSkipPriceAsinShopPage = 1, chooseSkipPriceAsinShopPageSize = 10; + var skipPriceCountryColumns = [ + { code: 'DE', field: 'asin_de', label: '寰峰浗' }, + { code: 'UK', field: 'asin_uk', label: '鑻卞浗' }, + { code: 'FR', field: 'asin_fr', label: '娉曞浗' }, + { code: 'IT', field: 'asin_it', label: '鎰忓ぇ鍒? }, + { code: 'ES', field: 'asin_es', label: '瑗跨彮鐗? } + ]; + function buildChooseSkipPriceAsinShopQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + chooseSkipPriceAsinShopPageSize; + var groupId = (document.getElementById('chooseSkipPriceAsinShopGroupId').value || '').trim(); + var shopName = (document.getElementById('chooseSkipPriceAsinShopKeyword').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + return query; + } + function loadChooseSkipPriceAsinShops(page) { + chooseSkipPriceAsinShopPage = page || 1; + fetch('/api/admin/shop-manages?' + buildChooseSkipPriceAsinShopQuery(chooseSkipPriceAsinShopPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('chooseSkipPriceAsinShopListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (!items.length) { + tbody.innerHTML = '鏆傛棤搴楅摵'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (chooseSkipPriceAsinShopPage - 1) * chooseSkipPriceAsinShopPageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + (item.mall_name || '') + '' + (item.account || '') + '' + + '' + + ''; + }).join(''); + } + renderPagination('chooseSkipPriceAsinShopPagination', res.total, res.page, res.page_size, loadChooseSkipPriceAsinShops); + bindChooseSkipPriceAsinShopActions(); + }) + .catch(function () { + document.getElementById('chooseSkipPriceAsinShopListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + function bindChooseSkipPriceAsinShopActions() { + document.querySelectorAll('[data-choose-skip-price-asin-shop]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('skipPriceAsinShopName').value = (btn.dataset.shopName || '').replace(/"/g, '"'); + if (!document.getElementById('skipPriceAsinGroupSelect').value && btn.dataset.groupId) { + document.getElementById('skipPriceAsinGroupSelect').value = btn.dataset.groupId; + } + document.getElementById('chooseSkipPriceAsinShopModal').classList.remove('show'); + }; + }); + } + function openChooseSkipPriceAsinShopModal() { + var currentGroupId = (document.getElementById('skipPriceAsinGroupSelect').value || '').trim(); + if (currentGroupId) { + document.getElementById('chooseSkipPriceAsinShopGroupId').value = currentGroupId; + } + document.getElementById('chooseSkipPriceAsinShopKeyword').value = (document.getElementById('skipPriceAsinShopName').value || '').trim(); + document.getElementById('chooseSkipPriceAsinShopModal').classList.add('show'); + loadChooseSkipPriceAsinShops(1); + } + function setupSkipPriceAsinShopPicker() { + var input = document.getElementById('skipPriceAsinShopName'); + var button = document.getElementById('btnChooseSkipPriceAsinShop'); + if (!input || !button) return; + var inputParent = input.parentNode; + if (inputParent && inputParent.style && inputParent.style.display === 'flex') return; + var legacyWrap = button.parentNode; + var wrapper = document.createElement('div'); + wrapper.style.display = 'flex'; + wrapper.style.gap = '8px'; + wrapper.style.alignItems = 'center'; + input.parentNode.insertBefore(wrapper, input); + wrapper.appendChild(input); + wrapper.appendChild(button); + button.style.whiteSpace = 'nowrap'; + button.style.marginTop = '0'; + if (legacyWrap && legacyWrap !== wrapper) { + legacyWrap.style.display = 'none'; + } + } + function getSelectedSkipPriceCountries() { + return Array.from(document.getElementById('skipPriceAsinCountries').selectedOptions).map(function (option) { + return option.value; + }); + } + function renderSkipPriceAsinInputs() { + var container = document.getElementById('skipPriceAsinInputs'); + var selectedCountries = getSelectedSkipPriceCountries(); + var existingValues = {}; + container.querySelectorAll('[data-skip-price-country-input]').forEach(function (input) { + existingValues[input.getAttribute('data-skip-price-country-input')] = input.value; + }); + if (!selectedCountries.length) { + container.innerHTML = '
璇烽€夋嫨鍥藉鍚庤緭鍏?ASIN
'; + return; + } + container.innerHTML = selectedCountries.map(function (countryCode) { + var country = skipPriceCountryColumns.find(function (item) { return item.code === countryCode; }); + var label = country ? country.label : countryCode; + var value = existingValues[countryCode] || ''; + return '
' + + '' + label + '' + + '' + + '
'; + }).join(''); + } + function collectSkipPriceAsinMappings(countries) { + var mappings = {}; + for (var i = 0; i < countries.length; i++) { + var countryCode = countries[i]; + var input = document.querySelector('[data-skip-price-country-input="' + countryCode + '"]'); + var asin = input ? (input.value || '').trim().toUpperCase() : ''; + if (!asin) { + var country = skipPriceCountryColumns.find(function (item) { return item.code === countryCode; }); + var label = country ? country.label : countryCode; + throw new Error(label + ' ASIN 涓嶈兘涓虹┖'); + } + mappings[countryCode] = asin; + } + return mappings; + } + function buildSkipPriceAsinQuery(page) { + var query = 'page=' + (page || 1) + '&page_size=' + skipPriceAsinPageSize; + var groupId = (document.getElementById('skipPriceAsinFilterGroupId').value || '').trim(); + var shopName = (document.getElementById('skipPriceAsinFilterShopName').value || '').trim(); + var asin = (document.getElementById('skipPriceAsinFilterAsin').value || '').trim(); + if (groupId) query += '&group_id=' + encodeURIComponent(groupId); + if (shopName) query += '&shop_name=' + encodeURIComponent(shopName); + if (asin) query += '&asin=' + encodeURIComponent(asin); + return query; + } + function renderSkipPriceAsinCell(item, country) { + var value = item[country.field] || ''; + if (!value) return '-'; + return '
' + + '' + value + '' + + '' + + '' + + '
'; + } + function bindSkipPriceAsinActions() { + document.querySelectorAll('[data-skip-price-asin-edit]').forEach(function (btn) { + btn.onclick = function () { + var shopName = (btn.dataset.shopName || '').replace(/"/g, '"'); + var countryCode = btn.dataset.country || ''; + var currentAsin = (btn.dataset.asin || '').replace(/"/g, '"'); + var nextAsin = prompt('璇疯緭鍏ュ簵閾衡€? + shopName + '鈥濆湪 ' + countryCode + ' 鐨?ASIN', currentAsin); + if (nextAsin === null) return; + nextAsin = (nextAsin || '').trim(); + if (!nextAsin) { + alert('ASIN 涓嶈兘涓虹┖'); + return; + } + fetch('/api/admin/skip-price-asin/' + btn.dataset.skipPriceAsinEdit + '/country/' + countryCode, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ asin: nextAsin }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) loadSkipPriceAsin(skipPriceAsinPage); + else alert(res.error || '淇濆瓨澶辫触'); + }); + }; + }); + document.querySelectorAll('[data-skip-price-asin-delete]').forEach(function (btn) { + btn.onclick = function () { + var shopName = (btn.dataset.shopName || '').replace(/"/g, '"'); + var countryCode = btn.dataset.country || ''; + if (!confirm('纭畾鍒犻櫎搴楅摵鈥? + shopName + '鈥濆湪 ' + countryCode + ' 鐨?ASIN 鍚楋紵')) return; + fetch('/api/admin/skip-price-asin/' + btn.dataset.skipPriceAsinDelete + '/country/' + countryCode, { + method: 'DELETE' + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) loadSkipPriceAsin(skipPriceAsinPage); + else alert(res.error || '鍒犻櫎澶辫触'); + }); + }; + }); + } + function loadSkipPriceAsin(page) { + skipPriceAsinPage = page || 1; + fetch('/api/admin/skip-price-asins?' + buildSkipPriceAsinQuery(skipPriceAsinPage)) + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('skipPriceAsinListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤鏁版嵁'; + } else { + tbody.innerHTML = items.map(function (item, index) { + var rowNo = (skipPriceAsinPage - 1) * skipPriceAsinPageSize + index + 1; + return '' + rowNo + '' + (item.group_name || '') + '' + (item.shop_name || '') + '' + + skipPriceCountryColumns.map(function (country) { + return '' + renderSkipPriceAsinCell(item, country) + ''; + }).join('') + + ''; + }).join(''); + } + renderPagination('skipPriceAsinPagination', res.total, res.page, res.page_size, loadSkipPriceAsin); + bindSkipPriceAsinActions(); + }) + .catch(function () { + document.getElementById('skipPriceAsinListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + document.getElementById('btnManageSkipPriceAsinGroups').onclick = openShopManageGroupModal; + document.getElementById('btnChooseSkipPriceAsinShop').onclick = openChooseSkipPriceAsinShopModal; + document.getElementById('btnSearchChooseSkipPriceAsinShop').onclick = function () { + loadChooseSkipPriceAsinShops(1); + }; + document.getElementById('chooseSkipPriceAsinShopGroupId').onchange = function () { + loadChooseSkipPriceAsinShops(1); + }; + document.getElementById('chooseSkipPriceAsinShopKeyword').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadChooseSkipPriceAsinShops(1); + } + }); + document.getElementById('btnCloseChooseSkipPriceAsinShopModal').onclick = function () { + document.getElementById('chooseSkipPriceAsinShopModal').classList.remove('show'); + }; + document.getElementById('skipPriceAsinCountries').addEventListener('change', renderSkipPriceAsinInputs); + document.getElementById('btnSearchSkipPriceAsin').onclick = function () { + loadSkipPriceAsin(1); + }; + document.getElementById('skipPriceAsinFilterShopName').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadSkipPriceAsin(1); + } + }); + document.getElementById('skipPriceAsinFilterAsin').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { + e.preventDefault(); + loadSkipPriceAsin(1); + } + }); + document.getElementById('btnCreateSkipPriceAsin').onclick = function () { + var groupId = (document.getElementById('skipPriceAsinGroupSelect').value || '').trim(); + var shopName = (document.getElementById('skipPriceAsinShopName').value || '').trim(); + var countries = getSelectedSkipPriceCountries(); + var msgEl = document.getElementById('msgSkipPriceAsin'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!groupId || !shopName || !countries.length) { + msgEl.textContent = '璇峰畬鏁村~鍐欏垎缁勩€佸簵閾哄悕銆佸浗瀹跺拰 ASIN'; + msgEl.className = 'msg err'; + return; + } + var asinMappings = {}; + try { + asinMappings = collectSkipPriceAsinMappings(countries); + } catch (err) { + msgEl.textContent = err.message || '璇疯緭鍏?ASIN'; + msgEl.className = 'msg err'; + return; + } + var fallbackAsin = ''; + Object.keys(asinMappings).some(function (countryCode) { + fallbackAsin = asinMappings[countryCode] || ''; + return !!fallbackAsin; + }); + fetch('/api/admin/skip-price-asin', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + group_id: Number(groupId), + shop_name: shopName, + countries: countries, + asin: fallbackAsin, + asin_mappings: asinMappings + }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (!res.success) { + msgEl.textContent = res.error || '淇濆瓨澶辫触'; + msgEl.className = 'msg err'; + return; + } + document.getElementById('skipPriceAsinGroupSelect').value = ''; + document.getElementById('skipPriceAsinShopName').value = ''; + Array.from(document.getElementById('skipPriceAsinCountries').options).forEach(function (option) { + option.selected = false; + }); + renderSkipPriceAsinInputs(); + msgEl.textContent = res.msg || '淇濆瓨鎴愬姛'; + msgEl.className = 'msg ok'; + loadSkipPriceAsin(1); + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.className = 'msg err'; + }); + }; + setupSkipPriceAsinShopPicker(); + renderSkipPriceAsinInputs(); + function loadVersions() { + fetch('/api/admin/versions') + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('versionListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + var items = res.items || []; + if (items.length === 0) { + tbody.innerHTML = '鏆傛棤鐗堟湰璁板綍'; + } else { + tbody.innerHTML = items.map(function (v) { + var url = (v.file_url || '').replace(/"/g, '"'); + return '' + (v.version || '') + '' + url + '' + (v.created_at || '') + '涓嬭浇'; + }).join(''); + } + }) + .catch(function () { + document.getElementById('versionListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + document.getElementById('btnUploadVersion').onclick = function () { + var version = (document.getElementById('versionNumber').value || '').trim(); + var fileInput = document.getElementById('versionZip'); + var msgEl = document.getElementById('msgVersion'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!version) { + msgEl.textContent = '璇峰~鍐欑増鏈彿'; + msgEl.classList.add('err'); + return; + } + if (!fileInput.files || fileInput.files.length === 0) { + msgEl.textContent = '璇烽€夋嫨 zip 鍘嬬缉鍖?; + msgEl.classList.add('err'); + return; + } + var file = fileInput.files[0]; + if (!(file.name || '').toLowerCase().endsWith('.zip')) { + msgEl.textContent = '浠呮敮鎸?.zip 鏍煎紡'; + msgEl.classList.add('err'); + return; + } + var formData = new FormData(); + formData.append('version', version); + formData.append('file', file); + msgEl.textContent = '涓婁紶涓?..'; + msgEl.classList.remove('err', 'ok'); + fetch('/api/admin/version', { + method: 'POST', + body: formData + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = '鍙戝竷鎴愬姛銆傜増鏈細' + res.version + '锛岄摼鎺ワ細' + (res.file_url || ''); + msgEl.classList.add('ok'); + document.getElementById('versionNumber').value = ''; + fileInput.value = ''; + loadVersions(); + } else { + msgEl.textContent = res.error || '涓婁紶澶辫触'; + msgEl.classList.add('err'); + } + }) + .catch(function () { + msgEl.textContent = '璇锋眰澶辫触'; + msgEl.classList.add('err'); + }); + }; + + // ========== 鏍忕洰鏉冮檺閰嶇疆 ========== + function loadColumns() { + fetch('/api/admin/columns') + .then(function (r) { return r.json(); }) + .then(function (res) { + var tbody = document.getElementById('columnListBody'); + if (!res.success) { + tbody.innerHTML = '鍔犺浇澶辫触: ' + (res.error || '') + ''; + return; + } + allColumnsList = res.items || []; + if (allColumnsList.length === 0) { + tbody.innerHTML = '鏆傛棤鑿滃崟锛岃鍦ㄤ笂鏂规柊澧?/td>'; + } else { + tbody.innerHTML = allColumnsList.map(function (c) { + return '' + c.id + '' + (c.name || '') + '' + (c.column_key || '') + '' + (c.created_at || '') + '' + + ' ' + + ''; + }).join(''); + } + bindColumnActions(); + }) + .catch(function () { + document.getElementById('columnListBody').innerHTML = '璇锋眰澶辫触'; + }); + } + function bindColumnActions() { + document.querySelectorAll('[data-column-edit]').forEach(function (btn) { + btn.onclick = function () { + document.getElementById('editColumnId').value = btn.dataset.columnEdit || ''; + document.getElementById('editColumnName').value = (btn.dataset.name || '').replace(/"/g, '"'); + document.getElementById('editColumnKey').value = (btn.dataset.key || '').replace(/"/g, '"'); + document.getElementById('msgEditColumn').textContent = ''; + document.getElementById('editColumnModal').classList.add('show'); + }; + }); + document.querySelectorAll('[data-column-delete]').forEach(function (btn) { + btn.onclick = function () { + if (!confirm('纭畾鍒犻櫎鑿滃崟鈥? + (btn.dataset.name || '').replace(/"/g, '"') + '鈥濆悧锛?)) return; + fetch('/api/admin/column/' + btn.dataset.columnDelete, { method: 'DELETE' }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { loadColumns(); loadColumnsForPermission(); loadAdminMenus(getActiveAdminTabName()); } + else { alert(res.error || '鍒犻櫎澶辫触'); } + }); + }; + }); + } + document.getElementById('btnAddColumn').onclick = function () { + var name = (document.getElementById('columnName').value || '').trim(); + var key = (document.getElementById('columnKey').value || '').trim(); + var msgEl = document.getElementById('msgColumn'); + msgEl.textContent = ''; + msgEl.className = 'msg'; + if (!name) { msgEl.textContent = '璇峰~鍐欒彍鍗曞悕绉?; msgEl.classList.add('err'); return; } + if (!key) { + msgEl.textContent = '璇峰~鍐欐爮鐩爣璇?; msgEl.classList.add('err'); return; + } + fetch('/api/admin/column', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: name, column_key: key }) + }) + .then(function (r) { return r.json(); }) + .then(function (res) { + if (res.success) { + msgEl.textContent = res.msg || '鏂板鎴愬姛'; + msgEl.classList.add('ok'); + document.getElementById('columnName').value = ''; + document.getElementById('columnKey').value = ''; + loadColumns(); + loadColumnsForPermission(); + loadAdminMenus(getActiveAdminTabName()); + } else { diff --git a/backend/web_source/admin.html b/backend/web_source/admin.html index 1fc9406..82837a5 100644 --- a/backend/web_source/admin.html +++ b/backend/web_source/admin.html @@ -1,20 +1,85 @@ - + + 管理后台 - 南日AI + - +

管理后台

-
+
+ 加载中... + + +
+ +
用户管理
栏目权限配置
数据去重总数据
@@ -120,22 +414,23 @@
-
+

创建用户

-

无注册入口,仅管理员可在此创建用户。层级:超级管理员 → 管理员 → 普通号。

+

+ 当前没有开放注册入口,仅管理员可在此创建用户。层级关系:超级管理员 -> 管理员 -> 普通账号。

- +
- +
@@ -146,7 +441,7 @@
- +
@@ -189,21 +484,32 @@
-

新增栏目

+

新增菜单

- - + +
-
+
- +
- +
+ + +
+
+ + +
+

@@ -213,8 +519,10 @@ ID - 栏目名 + 菜单名称 栏目标识 + 菜单类型 + 排序 菜单路由 创建时间 操作 @@ -271,7 +579,9 @@

@@ -286,7 +596,9 @@

@@ -299,7 +611,7 @@
- + @@ -325,11 +637,11 @@ -
+
- +

@@ -370,7 +682,7 @@ -
+
@@ -378,11 +690,11 @@
-
+
- +

@@ -439,8 +751,12 @@ -
+
+
+ + +
-
+
- +
+
请选择国家后输入对应 ASIN
+
@@ -544,13 +862,13 @@
- +
@@ -559,7 +877,7 @@
- +
@@ -580,7 +898,7 @@ -

+

@@ -594,10 +912,10 @@

编辑栏目

- - + +
-
+
@@ -605,6 +923,17 @@
+
+ + +
+
+ + +

@@ -619,9 +948,16 @@

分组管理

+
+ + +
- +
@@ -629,7 +965,14 @@

- + + + + + + + +
序号分组名称创建时间修改时间操作
序号分组名称关联用户创建时间修改时间操作
@@ -640,6 +983,44 @@ + +