修复:禁止批量铺货误读多工作表内容
- 按 workbook 关系定位唯一 XLSX 工作表并拒绝多表或损坏结构 - 重置表格文件控件以支持同一路径文件重新选择 - 补齐应用层、HTTP 与前端文件选择回归测试
This commit is contained in:
1 parent
58f91ac77d
commit
3b67ab81ee
18 files changed
+422
-26
No files matched your search
@@ -0,0 +1,36 @@
|
||||
// @vitest-environment jsdom
|
||||
// 本测试需要浏览器文件控件与 File API,因此固定使用 jsdom 环境。
|
||||
import { describe,expect,test } from 'vitest';
|
||||
import { consumeSelectedFile } from './fileInput';
|
||||
|
||||
// ItemList 文件选择测试覆盖同一路径的表格在保存后能够被重新读取。
|
||||
describe('consumeSelectedFile',
|
||||
// 测试组回调验证读取文件后重置原生 input 的浏览器兼容行为。
|
||||
() => {
|
||||
// 连续两次选择同名文件时,每次都返回对应 File 快照并清空上一轮原生选择值。
|
||||
test('clears the native input after each selected file',
|
||||
// 测试回调模拟浏览器在用户重新选择同一路径前写入的文件列表和伪路径值。
|
||||
() => {
|
||||
// input 保存可被测试替换 files 与 value 行为的文件控件。
|
||||
const input = document.createElement('input');
|
||||
// currentValue 保存浏览器文件控件的当前伪路径值,空值代表下次同一路径选择会重新触发 change。
|
||||
let currentValue = 'C:\\fakepath\\products.xlsx';
|
||||
Object.defineProperty(input, 'value', {
|
||||
configurable: true,
|
||||
get: /* 当前访问器返回模拟的文件控件伪路径。 */ () => currentValue,
|
||||
set: /* 当前访问器记录业务代码清空原生控件的操作。 */ value => { currentValue = String(value); },
|
||||
});
|
||||
// firstFile 保存首次选择时浏览器创建的文件快照。
|
||||
const firstFile = new File(['old-content'], 'products.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||
Object.defineProperty(input, 'files', { configurable: true, value: [firstFile] as unknown as FileList });
|
||||
expect(consumeSelectedFile(input)).toBe(firstFile);
|
||||
expect(currentValue).toBe('');
|
||||
|
||||
// secondFile 保存同名文件修改后再次选择时浏览器创建的新快照。
|
||||
const secondFile = new File(['new-content'], 'products.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||
currentValue = 'C:\\fakepath\\products.xlsx';
|
||||
Object.defineProperty(input, 'files', { configurable: true, value: [secondFile] as unknown as FileList });
|
||||
expect(consumeSelectedFile(input)).toBe(secondFile);
|
||||
expect(currentValue).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* consumeSelectedFile 读取文件控件当前选择的首个文件,并立即重置原生值。
|
||||
* input 是批量铺货表格控件;返回值是可由 React 状态持有的文件快照,重置让用户可再次选择相同路径的已修改文件。
|
||||
*/
|
||||
export const consumeSelectedFile = (input: HTMLInputElement): File | null => {
|
||||
// selectedFile 保存本次 change 事件携带的文件快照;无选择或用户取消时为 null。
|
||||
const selectedFile = input.files?.[0] || null;
|
||||
// 原生控件必须在读取后清空,否则浏览器可能将相同路径的再次选择视为未变化而不触发 change。
|
||||
input.value = '';
|
||||
return selectedFile;
|
||||
};
|
||||
@@ -10,6 +10,7 @@ getShippingRules,
|
||||
} from '../api';
|
||||
import { batchStatusClass,batchStatusText } from '../batchState';
|
||||
import { BatchPhaseIndicator } from '../components/BatchPhaseIndicator';
|
||||
import { consumeSelectedFile } from '../fileInput';
|
||||
import { useItemPublishBatch } from '../hooks';
|
||||
import { useItemActions } from '../itemActions';
|
||||
import type { ItemListProps } from '../types';
|
||||
@@ -676,7 +677,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
className="hidden"
|
||||
type="file"
|
||||
accept=".xlsx,.csv,.tsv"
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchFile(e.target.files?.[0] || null)}
|
||||
onChange={/* 当前回调读取本次文件快照并重置原生控件,以便同一路径文件修改后可再次选择。 */ event => setBatchFile(consumeSelectedFile(event.currentTarget))}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50 transition-colors">
|
||||
|
||||
@@ -374,7 +374,7 @@ func parseDelimitedSheet(raw []byte, delimiter rune, maxRows int) ([]map[string]
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// parseXLSXSheet 解析 XLSX 第一张工作表中的单元格文本。
|
||||
// parseXLSXSheet 解析 XLSX 唯一工作表中的单元格文本;多工作表文件会被拒绝以避免误读历史数据。
|
||||
func parseXLSXSheet(raw []byte, maxRows int) ([]map[string]any, error) {
|
||||
// archive 和 err 表示 XLSX 压缩包及打开错误。
|
||||
archive, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
|
||||
@@ -386,17 +386,10 @@ func parseXLSXSheet(raw []byte, maxRows int) ([]map[string]any, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// sheet 保存第一张工作表的压缩文件。
|
||||
var sheet *zip.File
|
||||
// file 表示当前遍历到的压缩包条目。
|
||||
for _, file := range archive.File {
|
||||
if strings.HasPrefix(file.Name, "xl/worksheets/sheet") && strings.HasSuffix(file.Name, ".xml") {
|
||||
sheet = file
|
||||
break
|
||||
}
|
||||
}
|
||||
if sheet == nil {
|
||||
return nil, errors.New("xlsx 中未找到工作表")
|
||||
// sheet 保存由 workbook 关系明确定位的唯一工作表,不能按 ZIP 条目顺序猜测用户编辑的数据页。
|
||||
sheet, err := xlsxSingleWorksheet(archive)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// part 和 err 表示工作表 XML 内容及读取错误。
|
||||
part, err := readXLSXPart(sheet)
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package items
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -77,6 +80,138 @@ func TestParseSheetRejectsEmptyAndUnsupportedInput(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseSheetUsesWorkbookRelationship 验证解析器按 workbook 关系读取唯一表,而不是误取 ZIP 内先出现的旧表。
|
||||
func TestParseSheetUsesWorkbookRelationship(t *testing.T) {
|
||||
// xlsx 保存含旧 sheet1 与当前 sheet9 的单工作表 XLSX;workbook 只声明 sheet9。
|
||||
xlsx := buildBatchPreviewXLSX(t, []batchPreviewSheetFixture{{Name: "当前数据", RelationshipID: "rId9", Target: "worksheets/sheet9.xml", Rows: [][]string{{"标题", "价格"}, {"新商品", "9.9"}}}}, map[string][][]string{
|
||||
"xl/worksheets/sheet1.xml": {{"标题", "价格"}, {"旧商品", "1.0"}},
|
||||
})
|
||||
// rows 和 err 分别保存解析结果及异常。
|
||||
rows, err := ParseSheet(xlsx, "products.xlsx", 2)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseSheet() error = %v", err)
|
||||
}
|
||||
if len(rows) != 1 || rows[0]["title"] != "新商品" {
|
||||
t.Fatalf("解析结果误读旧工作表: %#v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseSheetRejectsMultipleXLSXWorksheets 验证隐藏历史表与可见表并存时会被拒绝,避免预检读取非用户修改内容。
|
||||
func TestParseSheetRejectsMultipleXLSXWorksheets(t *testing.T) {
|
||||
// xlsx 保存两个 workbook 声明的工作表;第二个表代表复制文件遗留的隐藏历史表。
|
||||
xlsx := buildBatchPreviewXLSX(t, []batchPreviewSheetFixture{
|
||||
{Name: "当前数据", RelationshipID: "rId1", Target: "worksheets/sheet1.xml", Rows: [][]string{{"标题", "价格"}, {"新商品", "9.9"}}},
|
||||
{Name: "历史数据", RelationshipID: "rId2", Target: "worksheets/sheet2.xml", State: "hidden", Rows: [][]string{{"标题", "价格"}, {"旧商品", "1.0"}}},
|
||||
}, nil)
|
||||
// err 保存多工作表输入的预期拒绝错误。
|
||||
_, err := ParseSheet(xlsx, "products.xlsx", 2)
|
||||
if err == nil || !strings.Contains(err.Error(), "仅支持一个工作表") {
|
||||
t.Fatalf("多工作表应被拒绝,err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseSheetRejectsInvalidXLSXWorkbookRelationship 验证 sheet 引用缺少关系目标时不会回退到 ZIP 内任意工作表。
|
||||
func TestParseSheetRejectsInvalidXLSXWorkbookRelationship(t *testing.T) {
|
||||
// xlsx 保存唯一 sheet 声明指向不存在关系的损坏工作簿。
|
||||
xlsx := buildBatchPreviewXLSX(t, []batchPreviewSheetFixture{{Name: "当前数据", RelationshipID: "missing", Target: "worksheets/sheet1.xml", Rows: [][]string{{"标题", "价格"}, {"商品", "9.9"}}}}, nil)
|
||||
// err 保存损坏关系的预期结构错误。
|
||||
_, err := ParseSheet(xlsx, "products.xlsx", 2)
|
||||
if err == nil || !strings.Contains(err.Error(), "工作表结构无效") {
|
||||
t.Fatalf("无效关系应报结构错误,err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// batchPreviewSheetFixture 描述测试 XLSX 中一个 workbook 声明及其对应的单元格文本。
|
||||
type batchPreviewSheetFixture struct {
|
||||
// Name 是 workbook 中显示的工作表名称。
|
||||
Name string
|
||||
// RelationshipID 是 workbook sheet 节点引用的关系标识。
|
||||
RelationshipID string
|
||||
// Target 是关系文件中指向 worksheet XML 的相对路径。
|
||||
Target string
|
||||
// State 是可选的 Excel 工作表可见性状态,用于覆盖隐藏历史表。
|
||||
State string
|
||||
// Rows 是按行列写入 worksheet 的内联字符串文本。
|
||||
Rows [][]string
|
||||
}
|
||||
|
||||
// buildBatchPreviewXLSX 创建带 workbook 关系的最小 XLSX,用于覆盖工作表选择和结构错误场景。
|
||||
func buildBatchPreviewXLSX(t *testing.T, sheets []batchPreviewSheetFixture, extraParts map[string][][]string) []byte {
|
||||
t.Helper()
|
||||
// buffer 保存最终 ZIP 格式 XLSX 字节。
|
||||
var buffer bytes.Buffer
|
||||
// writer 负责写入 XLSX 的 workbook、关系和工作表 XML 分区。
|
||||
writer := zip.NewWriter(&buffer)
|
||||
// workbookBuilder 保存 workbook.xml 的 sheet 声明。
|
||||
var workbookBuilder strings.Builder
|
||||
workbookBuilder.WriteString(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>`)
|
||||
// relationshipsBuilder 保存 workbook.xml.rels 的关系记录。
|
||||
var relationshipsBuilder strings.Builder
|
||||
relationshipsBuilder.WriteString(`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`)
|
||||
// partName 和 rows 分别表示先写入 ZIP 的历史工作表分区及其旧内容,用于验证不能按物理条目顺序读取。
|
||||
for partName, rows := range extraParts {
|
||||
writeBatchPreviewXLSXPart(t, writer, partName, batchPreviewWorksheetXML(rows))
|
||||
}
|
||||
// sheetIndex 和 sheet 分别表示当前 sheet 序号与对应的测试定义。
|
||||
for sheetIndex, sheet := range sheets {
|
||||
// stateAttribute 保存有隐藏状态时写入 sheet XML 属性的片段。
|
||||
stateAttribute := ""
|
||||
if sheet.State != "" {
|
||||
stateAttribute = fmt.Sprintf(` state=%q`, sheet.State)
|
||||
}
|
||||
_, _ = fmt.Fprintf(&workbookBuilder, `<sheet name=%q sheetId="%d" r:id=%q%s/>`, sheet.Name, sheetIndex+1, sheet.RelationshipID, stateAttribute)
|
||||
if sheet.RelationshipID != "missing" {
|
||||
_, _ = fmt.Fprintf(&relationshipsBuilder, `<Relationship Id=%q Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target=%q/>`, sheet.RelationshipID, sheet.Target)
|
||||
}
|
||||
// partName 保存当前工作表在 ZIP 内的完整分区路径。
|
||||
partName := "xl/" + sheet.Target
|
||||
writeBatchPreviewXLSXPart(t, writer, partName, batchPreviewWorksheetXML(sheet.Rows))
|
||||
}
|
||||
workbookBuilder.WriteString(`</sheets></workbook>`)
|
||||
relationshipsBuilder.WriteString(`</Relationships>`)
|
||||
writeBatchPreviewXLSXPart(t, writer, "xl/workbook.xml", workbookBuilder.String())
|
||||
writeBatchPreviewXLSXPart(t, writer, "xl/_rels/workbook.xml.rels", relationshipsBuilder.String())
|
||||
// err 保存关闭 ZIP 写入器并写出末尾目录时的错误。
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("关闭 XLSX 写入器失败: %v", err)
|
||||
}
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
// writeBatchPreviewXLSXPart 在测试 XLSX 中写入一个 XML 分区,任一写入失败都立即终止测试。
|
||||
func writeBatchPreviewXLSXPart(t *testing.T, writer *zip.Writer, name, content string) {
|
||||
t.Helper()
|
||||
// part 和 err 分别保存新建 ZIP 分区的写入器及创建错误。
|
||||
part, err := writer.Create(name)
|
||||
if err != nil {
|
||||
t.Fatalf("创建 XLSX 分区失败: %v", err)
|
||||
}
|
||||
// err 保存将 XML 内容写入当前 ZIP 分区时的错误。
|
||||
if _, err := part.Write([]byte(content)); err != nil {
|
||||
t.Fatalf("写入 XLSX 分区失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// batchPreviewWorksheetXML 把二维单元格文本编码为解析器可读取的内联字符串工作表 XML。
|
||||
func batchPreviewWorksheetXML(rows [][]string) string {
|
||||
// builder 保存逐行拼接的 worksheet XML。
|
||||
var builder strings.Builder
|
||||
builder.WriteString(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>`)
|
||||
// rowIndex 和 row 分别表示当前行的零基下标及单元格集合。
|
||||
for rowIndex, row := range rows {
|
||||
_, _ = fmt.Fprintf(&builder, `<row r="%d">`, rowIndex+1)
|
||||
// columnIndex 和 value 分别表示当前列的零基下标及其可见文本。
|
||||
for columnIndex, value := range row {
|
||||
// reference 保存 A1 形式的单元格坐标;测试列数很小,仅覆盖单字母列。
|
||||
reference := fmt.Sprintf("%c%d", 'A'+rune(columnIndex), rowIndex+1)
|
||||
_, _ = fmt.Fprintf(&builder, `<c r=%q t="inlineStr"><is><t>%s</t></is></c>`, reference, value)
|
||||
}
|
||||
builder.WriteString(`</row>`)
|
||||
}
|
||||
builder.WriteString(`</sheetData></worksheet>`)
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// TestBatchPreviewValidatesBusinessRules 验证预检服务的归属、金额、类目、图片和自动化规则。
|
||||
func TestBatchPreviewValidatesBusinessRules(t *testing.T) {
|
||||
// service 和 err 表示批量预检服务及构造错误。
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package items
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// xlsxWorkbook 保存 workbook.xml 中声明的用户可见或隐藏工作表;批量铺货只接受其中恰好一个表。
|
||||
type xlsxWorkbook struct {
|
||||
// Sheets 保存工作簿声明的全部工作表,隐藏表同样必须参与计数以避免误读历史数据。
|
||||
Sheets struct {
|
||||
// Items 保存每个工作表的关系标识和展示名称。
|
||||
Items []xlsxWorkbookSheet `xml:"sheet"`
|
||||
} `xml:"sheets"`
|
||||
}
|
||||
|
||||
// xlsxWorkbookSheet 保存 workbook.xml 中单个工作表到关系文件的引用。
|
||||
type xlsxWorkbookSheet struct {
|
||||
// Name 是工作表名称,仅用于结构校验与诊断,不会写入预检结果。
|
||||
Name string `xml:"name,attr"`
|
||||
// RelationshipID 是 workbook 关系文件中定位实际 XML 分区的标识。
|
||||
RelationshipID string `xml:"id,attr"`
|
||||
}
|
||||
|
||||
// xlsxRelationships 保存 workbook.xml.rels 中的关系集合。
|
||||
type xlsxRelationships struct {
|
||||
// Items 保存每一条关系及其目标文件。
|
||||
Items []xlsxRelationship `xml:"Relationship"`
|
||||
}
|
||||
|
||||
// xlsxRelationship 保存工作簿关系文件的一条内部或外部关系。
|
||||
type xlsxRelationship struct {
|
||||
// ID 是 workbook.xml 中 sheet 元素引用的唯一关系标识。
|
||||
ID string `xml:"Id,attr"`
|
||||
// Target 是相对 workbook.xml 所在目录的目标分区路径。
|
||||
Target string `xml:"Target,attr"`
|
||||
// TargetMode 为 External 时表示目标不在上传压缩包内,不能作为本地工作表读取。
|
||||
TargetMode string `xml:"TargetMode,attr"`
|
||||
}
|
||||
|
||||
// xlsxSingleWorksheet 从 workbook 元数据定位唯一工作表,并拒绝包含多个表的上传文件。
|
||||
func xlsxSingleWorksheet(archive *zip.Reader) (*zip.File, error) {
|
||||
// workbookPart 和 err 分别保存 workbook.xml 的受限内容及读取失败原因。
|
||||
workbookPart, err := readXLSXPartNamed(archive, "xl/workbook.xml")
|
||||
if err != nil {
|
||||
return nil, errors.New("XLSX 工作表结构无效")
|
||||
}
|
||||
// workbook 保存 workbook.xml 反序列化后的工作表声明。
|
||||
var workbook xlsxWorkbook
|
||||
if xml.Unmarshal(workbookPart, &workbook) != nil || len(workbook.Sheets.Items) == 0 {
|
||||
return nil, errors.New("XLSX 工作表结构无效")
|
||||
}
|
||||
if len(workbook.Sheets.Items) != 1 {
|
||||
return nil, errors.New("批量铺货 XLSX 仅支持一个工作表,请删除多余工作表或另存为单工作表 CSV/XLSX 后重试")
|
||||
}
|
||||
// sheetDeclaration 保存唯一工作表的关系引用。
|
||||
sheetDeclaration := workbook.Sheets.Items[0]
|
||||
if strings.TrimSpace(sheetDeclaration.Name) == "" || strings.TrimSpace(sheetDeclaration.RelationshipID) == "" {
|
||||
return nil, errors.New("XLSX 工作表结构无效")
|
||||
}
|
||||
// relationshipsPart 和 err 分别保存关系文件内容及读取失败原因。
|
||||
relationshipsPart, err := readXLSXPartNamed(archive, "xl/_rels/workbook.xml.rels")
|
||||
if err != nil {
|
||||
return nil, errors.New("XLSX 工作表结构无效")
|
||||
}
|
||||
// relationships 保存关系文件反序列化后的目标列表。
|
||||
var relationships xlsxRelationships
|
||||
if xml.Unmarshal(relationshipsPart, &relationships) != nil {
|
||||
return nil, errors.New("XLSX 工作表结构无效")
|
||||
}
|
||||
// relationship 保存与唯一工作表标识匹配的内部关系。
|
||||
var relationship *xlsxRelationship
|
||||
// index 表示当前关系在关系集合中的位置。
|
||||
for index := range relationships.Items {
|
||||
// candidate 保存当前关系的可修改引用,避免循环变量地址失效。
|
||||
candidate := &relationships.Items[index]
|
||||
if candidate.ID == sheetDeclaration.RelationshipID {
|
||||
relationship = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if relationship == nil || strings.EqualFold(strings.TrimSpace(relationship.TargetMode), "External") {
|
||||
return nil, errors.New("XLSX 工作表结构无效")
|
||||
}
|
||||
// sheetPath 和 valid 分别保存归一化后的内部 XML 路径及安全校验结果。
|
||||
sheetPath, valid := xlsxWorkbookTargetPath(relationship.Target)
|
||||
if !valid {
|
||||
return nil, errors.New("XLSX 工作表结构无效")
|
||||
}
|
||||
// file 表示压缩包内与 workbook 关系精确匹配的工作表 XML。
|
||||
for _, file := range archive.File {
|
||||
if file.Name == sheetPath {
|
||||
return file, nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("XLSX 工作表结构无效")
|
||||
}
|
||||
|
||||
// readXLSXPartNamed 在压缩包中读取指定 XML 分区,并继续使用统一的解压大小限制。
|
||||
func readXLSXPartNamed(archive *zip.Reader, partName string) ([]byte, error) {
|
||||
// file 表示当前检查的 ZIP 条目。
|
||||
for _, file := range archive.File {
|
||||
if file.Name == partName {
|
||||
return readXLSXPart(file)
|
||||
}
|
||||
}
|
||||
return nil, errors.New("XLSX 分区不存在")
|
||||
}
|
||||
|
||||
// xlsxWorkbookTargetPath 将 workbook 相对关系目标解析为受限的 xl 内部路径。
|
||||
func xlsxWorkbookTargetPath(target string) (string, bool) {
|
||||
// trimmed 保存移除外围空白后的关系目标。
|
||||
trimmed := strings.TrimSpace(target)
|
||||
if trimmed == "" {
|
||||
return "", false
|
||||
}
|
||||
// candidate 保存兼容绝对与相对关系目标后的未清理路径。
|
||||
candidate := trimmed
|
||||
if strings.HasPrefix(candidate, "/") {
|
||||
candidate = strings.TrimPrefix(candidate, "/")
|
||||
} else {
|
||||
candidate = path.Join("xl", candidate)
|
||||
}
|
||||
// normalized 保存使用 ZIP 正斜杠规则清理后的内部路径。
|
||||
normalized := path.Clean(candidate)
|
||||
if !strings.HasPrefix(normalized, "xl/") || !strings.HasSuffix(normalized, ".xml") {
|
||||
return "", false
|
||||
}
|
||||
return normalized, true
|
||||
}
|
||||
@@ -166,6 +166,93 @@ func TestPreviewItemPublishBatchCSV(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPreviewItemPublishBatchRejectsMultipleXLSXWorksheets 验证预检会拒绝含隐藏历史表的 XLSX,且不会留下可启动批次或上传目录。
|
||||
func TestPreviewItemPublishBatchRejectsMultipleXLSXWorksheets(t *testing.T) {
|
||||
// uploadRoot 保存本测试独占的上传根目录,便于断言错误请求的临时文件已清理。
|
||||
uploadRoot := t.TempDir()
|
||||
t.Setenv("XIANYU_UPLOAD_DIR", uploadRoot)
|
||||
// srv、store、cleanup 分别保存测试 HTTP 服务、批次仓储和关闭函数。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 保存已配置路由与鉴权的测试入口。
|
||||
handler := srv.Router()
|
||||
// sessionCookie 保存管理员身份的 HTTP 会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
// xlsx 保存包含当前数据页和隐藏历史页的上传内容。
|
||||
xlsx := buildMultipleWorksheetPublishXLSX(t)
|
||||
// body 保存 multipart 请求的完整字节。
|
||||
var body bytes.Buffer
|
||||
// writer 负责编码预检接口要求的表单字段和 XLSX 文件。
|
||||
writer := multipart.NewWriter(&body)
|
||||
_ = writer.WriteField("default_cookie_id", "acc1")
|
||||
// spreadsheet 和 createErr 分别保存 XLSX 字段写入器及其创建错误。
|
||||
spreadsheet, createErr := writer.CreateFormFile("file", "products.xlsx")
|
||||
if createErr != nil {
|
||||
t.Fatalf("创建 XLSX 请求字段失败: %v", createErr)
|
||||
}
|
||||
// writeErr 保存将多工作表 XLSX 写入 multipart 字段时的错误。
|
||||
if _, writeErr := spreadsheet.Write(xlsx); writeErr != nil {
|
||||
t.Fatalf("写入 XLSX 请求字段失败: %v", writeErr)
|
||||
}
|
||||
// closeErr 保存完成 multipart 编码时写出尾部边界的错误。
|
||||
if closeErr := writer.Close(); closeErr != nil {
|
||||
t.Fatalf("关闭 multipart 请求失败: %v", closeErr)
|
||||
}
|
||||
// request 保存携带登录会话的预检 HTTP 请求。
|
||||
request := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &body)
|
||||
request.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
request.AddCookie(sessionCookie)
|
||||
// recorder 保存处理器返回的状态和统一错误 envelope。
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), "仅支持一个工作表") {
|
||||
t.Fatalf("多工作表预检应返回明确 400: status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
// batches 和 listErr 分别保存错误请求后的持久化批次列表及查询错误。
|
||||
batches, listErr := store.PublishBatches.ListForUser(context.Background(), 1, 10)
|
||||
if listErr != nil || len(batches) != 0 {
|
||||
t.Fatalf("错误预检不应创建批次: batches=%+v err=%v", batches, listErr)
|
||||
}
|
||||
// entries 和 readErr 分别保存批次上传目录的剩余条目及读取错误。
|
||||
entries, readErr := os.ReadDir(filepath.Join(uploadRoot, "publish_batches"))
|
||||
if readErr != nil && !os.IsNotExist(readErr) {
|
||||
t.Fatalf("读取上传目录失败: %v", readErr)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("错误预检不应保留上传目录: %+v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
// buildMultipleWorksheetPublishXLSX 创建一个物理条目顺序包含旧表、且 workbook 声明两个表的最小 XLSX。
|
||||
func buildMultipleWorksheetPublishXLSX(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
// buffer 保存最终 XLSX ZIP 字节。
|
||||
var buffer bytes.Buffer
|
||||
// writer 负责写入 XLSX 的各 XML 分区。
|
||||
writer := zip.NewWriter(&buffer)
|
||||
// writePart 把给定 XML 写入 ZIP;测试夹具写入失败必须立即终止。
|
||||
writePart := func(name, content string) {
|
||||
// part 和 createErr 分别保存 ZIP 分区写入器及其创建错误。
|
||||
part, createErr := writer.Create(name)
|
||||
if createErr != nil {
|
||||
t.Fatalf("创建 XLSX 分区失败: %v", createErr)
|
||||
}
|
||||
// writeErr 保存将当前 XML 字符串写入 ZIP 分区时的错误。
|
||||
if _, writeErr := part.Write([]byte(content)); writeErr != nil {
|
||||
t.Fatalf("写入 XLSX 分区失败: %v", writeErr)
|
||||
}
|
||||
}
|
||||
writePart("xl/worksheets/sheet1.xml", `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>标题</t></is></c><c r="B1" t="inlineStr"><is><t>价格</t></is></c></row><row r="2"><c r="A2" t="inlineStr"><is><t>旧商品</t></is></c><c r="B2" t="inlineStr"><is><t>1.0</t></is></c></row></sheetData></worksheet>`)
|
||||
writePart("xl/worksheets/sheet2.xml", `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>标题</t></is></c><c r="B1" t="inlineStr"><is><t>价格</t></is></c></row><row r="2"><c r="A2" t="inlineStr"><is><t>新商品</t></is></c><c r="B2" t="inlineStr"><is><t>9.9</t></is></c></row></sheetData></worksheet>`)
|
||||
writePart("xl/workbook.xml", `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="当前数据" sheetId="1" r:id="rId1"/><sheet name="历史数据" sheetId="2" state="hidden" r:id="rId2"/></sheets></workbook>`)
|
||||
writePart("xl/_rels/workbook.xml.rels", `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet2.xml"/></Relationships>`)
|
||||
// closeErr 保存写出 XLSX ZIP 尾部目录时的错误。
|
||||
if closeErr := writer.Close(); closeErr != nil {
|
||||
t.Fatalf("关闭 XLSX 写入器失败: %v", closeErr)
|
||||
}
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
// TestPreviewItemPublishBatchAllowsEmptyDefaultCategory 封装TestPreview商品发布批次AllowsEmptyDefault分类业务协调。
|
||||
func TestPreviewItemPublishBatchAllowsEmptyDefaultCategory(t *testing.T) {
|
||||
// srv、cleanup 用于本次流程后续判断的srv、cleanup
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
import{b as ie,j as e,a as l,d as Me}from"./react-vendor-Bf9ELcll.js";import{r as T,c as L}from"./index-BcKVxEYs.js";import{c as Ae,o as Pe}from"./contract-COFcZjyb.js";import{n as de,X as ce,f as Be,L as J,o as qe,p as Ge,q as Oe,r as Te,s as Le,U as Ie,t as te,u as ze,k as _e,Q as we,v as Ee,R as We,w as Ve,x as Ke,y as Ne,K as He,z as Je,F as Xe,e as Ye,H as Ze}from"./icons-vendor-B5fJPoU1.js";import"./vendor-BE-_xUHH.js";const Fe=(a,s)=>{const t=a.avatar_url||"";if(!t)return"";try{const r=new URL(t,window.location.origin);return r.hostname.endsWith("alicdn.com")&&r.searchParams.set("_v",s),r.toString()}catch{return t}},es=async a=>{const s=await T(n=>L.GET("/api/v1/accounts/details",{signal:n}),a),t=Ae(s,["data","accounts","details"]),r=Date.now().toString();return t.map(n=>({id:n.id,cookie_configured:n.has_cookie===!0,enabled:n.enabled,auto_confirm:n.auto_confirm,remark:n.remark,pause_duration:n.pause_duration,paused_until:Number(n.paused_until||0),paused:n.paused===!0,username:n.username||"",login_password_configured:void 0,show_browser:n.show_browser===!0||n.show_browser===1||n.show_browser==="1"||n.show_browser==="true",nickname:n.nickname||n.remark||`账号 ${n.id.substring(0,6)}`,avatar_url:Fe(n,r),profile_error:n.profile_error||"",ai_enabled:!1,auto_rate_enabled:n.auto_rate_enabled,rate_content:n.rate_content||"不错的买家,交易愉快",auto_polish_enabled:n.auto_polish_enabled,polish_time:n.polish_time||"03:00",last_rate_scan_at:Number(n.last_rate_scan_at||0),last_polish_date:n.last_polish_date||"",last_polish_at:Number(n.last_polish_at||0)}))},ve=async(a,s)=>T(t=>L.GET("/api/v1/account-tasks/{cid}",{params:{path:{cid:a}},signal:t}),s),ke=async(a,s,t)=>T(r=>L.PUT("/api/v1/account-tasks/{cid}",{params:{path:{cid:a}},body:s,signal:r}),t),ss=async(a,s,t)=>T(r=>L.POST("/api/v1/account-tasks/{cid}/run",{params:{path:{cid:a}},body:{task_type:s},signal:r}),{timeoutMs:12e4,...t}),as=async a=>await T(t=>L.GET("/api/v1/accounts/runtime-status",{signal:t}),a),ts=async a=>T(s=>L.POST("/api/v1/qr-login/generate",{signal:s}),{...a,timeoutMs:(a==null?void 0:a.timeoutMs)??13e4}),rs=async(a,s)=>T(t=>L.GET("/api/v1/qr-login/check/{session_id}",{params:{path:{session_id:a}},signal:t}),{signal:s,timeoutMs:1e4}),ns=async(a,s)=>T(t=>L.POST("/api/v1/qr-login/complete-verification/{session_id}",{params:{path:{session_id:a}},body:{target_account_id:s||""},signal:t})),ls=async(a,s)=>T(t=>L.PUT("/api/v1/accounts/{cid}/status",{params:{path:{cid:a}},body:{enabled:s},signal:t})),os=async a=>T(s=>L.DELETE("/api/v1/accounts/{cid}",{params:{path:{cid:a}},signal:s})),is=async(a,s,t)=>T(r=>L.PUT("/api/v1/accounts/{cid}/pause-duration",{params:{path:{cid:a}},body:{pause_duration:s},signal:r}),t),cs=async(a,s,t)=>T(r=>L.PUT("/api/v1/accounts/{cid}/settings",{params:{path:{cid:a}},body:s,signal:r}),t),ds=async(a,s)=>T(t=>L.GET("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:a}},signal:t}),s),us=async(a,s,t)=>T(r=>L.PUT("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:a}},body:{enabled:s},signal:r}),t),xs=async(a,s)=>T(t=>L.POST("/api/v1/password-login",{body:a,signal:t}),s),ms=async(a,s)=>T(r=>L.GET("/api/v1/password-login/check/{session_id}",{params:{path:{session_id:a}},signal:r}),{signal:s,timeoutMs:1e4}),bs=async(a,s)=>T(t=>L.DELETE("/api/v1/password-login/cancel/{session_id}",{params:{path:{session_id:a}},signal:t}),s),hs=async a=>T(s=>L.POST("/api/v1/accounts/{cid}/refresh-profile",{params:{path:{cid:a}},signal:s})),gs=async a=>{const s=await T(t=>L.GET("/api/v1/settings/ai-reply",{signal:t}),a);return Pe(s,["settings","data","result"])||{}},ps=async(a,s)=>T(t=>L.GET("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:a}},signal:t}),s),fs=async(a,s,t)=>{const r={ai_enabled:s.ai_enabled??!1,auto_adjust_price_enabled:s.auto_adjust_price_enabled??!1,max_discount_percent:s.max_discount_percent??10,max_discount_amount:s.max_discount_amount??100,max_bargain_rounds:s.max_bargain_rounds??3,custom_prompts:s.custom_prompts??""};return T(n=>L.PUT("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:a}},body:r,signal:n}),t)},ys=a=>{if(Array.isArray(a))return a.filter(Boolean);if(typeof a!="string"||!a.trim())return[];try{const s=JSON.parse(a);if(Array.isArray(s))return s.filter(Boolean)}catch{}return a.split(/[,\s;]+/).map(s=>s.trim()).filter(Boolean)},js=async a=>{const s=await T(r=>L.GET("/api/v1/notifications/channels",{signal:r}),a);return{success:!0,data:Ae(s,["data","channels","items"]).map(r=>{const n={},c=r.type==="ding_talk"?"dingtalk":r.type==="lark"?"feishu":r.type;return{id:String(r.id),name:r.name,type:c,config:n,event_types:ys(r.event_types),enabled:r.enabled}})}},_s=async(a,s)=>{const t=await T(n=>L.GET("/api/v1/notifications/accounts/{cid}/bindings",{params:{path:{cid:a}},signal:n}),s),r=Pe(t,["data","result"])||{};return Array.isArray(r.channel_ids)?r.channel_ids:[]},ws=({account:a,settings:s,saving:t,onChange:r,onClose:n,onSave:c})=>{const i=y=>r({...s,...y}),d=()=>i(s.ai_enaLine truncated
|
||||
import{b as ie,j as e,a as l,d as Me}from"./react-vendor-Bf9ELcll.js";import{r as T,c as L}from"./index-C6RECy_0.js";import{c as Ae,o as Pe}from"./contract-COFcZjyb.js";import{n as de,X as ce,f as Be,L as J,o as qe,p as Ge,q as Oe,r as Te,s as Le,U as Ie,t as te,u as ze,k as _e,Q as we,v as Ee,R as We,w as Ve,x as Ke,y as Ne,K as He,z as Je,F as Xe,e as Ye,H as Ze}from"./icons-vendor-B5fJPoU1.js";import"./vendor-BE-_xUHH.js";const Fe=(a,s)=>{const t=a.avatar_url||"";if(!t)return"";try{const r=new URL(t,window.location.origin);return r.hostname.endsWith("alicdn.com")&&r.searchParams.set("_v",s),r.toString()}catch{return t}},es=async a=>{const s=await T(n=>L.GET("/api/v1/accounts/details",{signal:n}),a),t=Ae(s,["data","accounts","details"]),r=Date.now().toString();return t.map(n=>({id:n.id,cookie_configured:n.has_cookie===!0,enabled:n.enabled,auto_confirm:n.auto_confirm,remark:n.remark,pause_duration:n.pause_duration,paused_until:Number(n.paused_until||0),paused:n.paused===!0,username:n.username||"",login_password_configured:void 0,show_browser:n.show_browser===!0||n.show_browser===1||n.show_browser==="1"||n.show_browser==="true",nickname:n.nickname||n.remark||`账号 ${n.id.substring(0,6)}`,avatar_url:Fe(n,r),profile_error:n.profile_error||"",ai_enabled:!1,auto_rate_enabled:n.auto_rate_enabled,rate_content:n.rate_content||"不错的买家,交易愉快",auto_polish_enabled:n.auto_polish_enabled,polish_time:n.polish_time||"03:00",last_rate_scan_at:Number(n.last_rate_scan_at||0),last_polish_date:n.last_polish_date||"",last_polish_at:Number(n.last_polish_at||0)}))},ve=async(a,s)=>T(t=>L.GET("/api/v1/account-tasks/{cid}",{params:{path:{cid:a}},signal:t}),s),ke=async(a,s,t)=>T(r=>L.PUT("/api/v1/account-tasks/{cid}",{params:{path:{cid:a}},body:s,signal:r}),t),ss=async(a,s,t)=>T(r=>L.POST("/api/v1/account-tasks/{cid}/run",{params:{path:{cid:a}},body:{task_type:s},signal:r}),{timeoutMs:12e4,...t}),as=async a=>await T(t=>L.GET("/api/v1/accounts/runtime-status",{signal:t}),a),ts=async a=>T(s=>L.POST("/api/v1/qr-login/generate",{signal:s}),{...a,timeoutMs:(a==null?void 0:a.timeoutMs)??13e4}),rs=async(a,s)=>T(t=>L.GET("/api/v1/qr-login/check/{session_id}",{params:{path:{session_id:a}},signal:t}),{signal:s,timeoutMs:1e4}),ns=async(a,s)=>T(t=>L.POST("/api/v1/qr-login/complete-verification/{session_id}",{params:{path:{session_id:a}},body:{target_account_id:s||""},signal:t})),ls=async(a,s)=>T(t=>L.PUT("/api/v1/accounts/{cid}/status",{params:{path:{cid:a}},body:{enabled:s},signal:t})),os=async a=>T(s=>L.DELETE("/api/v1/accounts/{cid}",{params:{path:{cid:a}},signal:s})),is=async(a,s,t)=>T(r=>L.PUT("/api/v1/accounts/{cid}/pause-duration",{params:{path:{cid:a}},body:{pause_duration:s},signal:r}),t),cs=async(a,s,t)=>T(r=>L.PUT("/api/v1/accounts/{cid}/settings",{params:{path:{cid:a}},body:s,signal:r}),t),ds=async(a,s)=>T(t=>L.GET("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:a}},signal:t}),s),us=async(a,s,t)=>T(r=>L.PUT("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:a}},body:{enabled:s},signal:r}),t),xs=async(a,s)=>T(t=>L.POST("/api/v1/password-login",{body:a,signal:t}),s),ms=async(a,s)=>T(r=>L.GET("/api/v1/password-login/check/{session_id}",{params:{path:{session_id:a}},signal:r}),{signal:s,timeoutMs:1e4}),bs=async(a,s)=>T(t=>L.DELETE("/api/v1/password-login/cancel/{session_id}",{params:{path:{session_id:a}},signal:t}),s),hs=async a=>T(s=>L.POST("/api/v1/accounts/{cid}/refresh-profile",{params:{path:{cid:a}},signal:s})),gs=async a=>{const s=await T(t=>L.GET("/api/v1/settings/ai-reply",{signal:t}),a);return Pe(s,["settings","data","result"])||{}},ps=async(a,s)=>T(t=>L.GET("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:a}},signal:t}),s),fs=async(a,s,t)=>{const r={ai_enabled:s.ai_enabled??!1,auto_adjust_price_enabled:s.auto_adjust_price_enabled??!1,max_discount_percent:s.max_discount_percent??10,max_discount_amount:s.max_discount_amount??100,max_bargain_rounds:s.max_bargain_rounds??3,custom_prompts:s.custom_prompts??""};return T(n=>L.PUT("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:a}},body:r,signal:n}),t)},ys=a=>{if(Array.isArray(a))return a.filter(Boolean);if(typeof a!="string"||!a.trim())return[];try{const s=JSON.parse(a);if(Array.isArray(s))return s.filter(Boolean)}catch{}return a.split(/[,\s;]+/).map(s=>s.trim()).filter(Boolean)},js=async a=>{const s=await T(r=>L.GET("/api/v1/notifications/channels",{signal:r}),a);return{success:!0,data:Ae(s,["data","channels","items"]).map(r=>{const n={},c=r.type==="ding_talk"?"dingtalk":r.type==="lark"?"feishu":r.type;return{id:String(r.id),name:r.name,type:c,config:n,event_types:ys(r.event_types),enabled:r.enabled}})}},_s=async(a,s)=>{const t=await T(n=>L.GET("/api/v1/notifications/accounts/{cid}/bindings",{params:{path:{cid:a}},signal:n}),s),r=Pe(t,["data","result"])||{};return Array.isArray(r.channel_ids)?r.channel_ids:[]},ws=({account:a,settings:s,saving:t,onChange:r,onClose:n,onSave:c})=>{const i=y=>r({...s,...y}),d=()=>i(s.ai_enaLine truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Be,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 只有开启自动改价后,已发送给买家的有效报价才会用于真实订单改价"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:n,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:t,children:"取消"}),e.jsxs("button",{onClick:(()=>void c()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:t,children:[t?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx(qe,{className:"w-4 h-4"}),t?"保存中...":"保存"]})]})})]})}),document.body)},Ce=a=>({account_id:a.id,auto_rate_enabled:a.auto_rate_enabled===!0,rate_content:a.rate_content||"不错的买家,交易愉快",auto_polish_enabled:a.auto_polish_enabled===!0,polish_time:a.polish_time||"03:00",last_rate_scan_at:a.last_rate_scan_at,last_polish_date:a.last_polish_date,last_polish_at:a.last_polish_at}),Z=(a,s,t)=>a===s&&!t.aborted,ye=(a,s)=>a instanceof Error?a.message:s,je=a=>a instanceof Error&&a.message==="请求已取消",Se=(a,s)=>!a&&s==="",Ns=({account:a,onSaved:s})=>{const[t,r]=l.useState(()=>Ce(a)),[n,c]=l.useState(!0),[i,d]=l.useState(!1),[m,x]=l.useState(""),[f,b]=l.useState(""),[h,y]=l.useState(null),[C,g]=l.useState(null),p=l.useRef(0),I=l.useRef(null);l.useEffect(()=>{var v;const R=++p.current;(v=I.current)==null||v.abort();const _=new AbortController;return I.current=_,r(Ce(a)),y(null),b(""),d(!1),x(""),g(null),c(!0),ve(a.id,{signal:_.signal}).then(A=>{Z(p.current,R,_.signal)&&r(A)}).catch(A=>{Z(p.current,R,_.signal)&&!je(A)&&b(ye(A,"加载任务设置失败"))}).finally(()=>{Z(p.current,R,_.signal)&&c(!1)}),(()=>_.abort())},[a.id]),l.useEffect(()=>(()=>{var R;return(R=I.current)==null?void 0:R.abort()}),[]);const B=l.useCallback(async()=>{var v;if(!Se(i,m))return;const R=++p.current;(v=I.current)==null||v.abort();const _=new AbortController;I.current=_,d(!0),b(""),g(null);try{const A=await ke(a.id,t,{signal:_.signal});if(!Z(p.current,R,_.signal))return;r(A),s(A)}catch(A){Z(p.current,R,_.signal)&&!je(A)&&(b(ye(A,"保存失败")),g(()=>B))}finally{Z(p.current,R,_.signal)&&d(!1)}},[a.id,t,s,m,i]),G=l.useCallback(async R=>{var A;if(!Se(i,m)||!a.enabled)return;const _=++p.current;(A=I.current)==null||A.abort();const v=new AbortController;I.current=v,x(R),b(""),y(null),g(null);try{await ke(a.id,t,{signal:v.signal});const N=await ss(a.id,R,{signal:v.signal}),P=await ve(a.id,{signal:v.signal});if(!Z(p.current,_,v.signal))return;y(N.summary),r(P),s(P)}catch(N){Z(p.current,_,v.signal)&&!je(N)&&(b(ye(N,"任务执行失败")),g(()=>(()=>G(R))))}finally{Z(p.current,_,v.signal)&&x("")}},[a.enabled,a.id,t,s,m,i]),D=l.useCallback(async()=>{C&&await C()},[C]);return{form:t,loading:n,saving:i,running:m,summary:h,error:f,retryAvailable:C!==null,setForm:r,save:B,run:G,retry:D}},Re=({checked:a,onChange:s,label:t})=>e.jsx("button",{type:"button","aria-label":t,"aria-pressed":a,onClick:s,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${a?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${a?"translate-x-6":""}`})}),vs=({account:a,onClose:s,onSaved:t})=>{const{form:r,loading:n,saving:c,running:i,error:d,summary:m,retryAvailable:x,setForm:f,save:b,run:h,retry:y}=Ns({account:a,onSaved:t});return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:a.nickname||a.remark||a.id})]}),e.jsx("button",{type:"button",onClick:s,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(ce,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[n&&e.jsx("div",{className:"rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500",children:"正在读取任务设置..."}),e.jsx("section",{
Line truncated
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import{a as c,b as U,j as e}from"./react-vendor-Bf9ELcll.js";import{r as M,c as O,a as ee}from"./index-BcKVxEYs.js";import{c as te}from"./contract-COFcZjyb.js";import{X as V,W as ae,J as z,Y as se,L as q,N as J,C as X,_ as le,$ as Y,a0 as K,a1 as ne,I as re,a2 as oe,V as ce,y as ie,P as de,o as xe}from"./icons-vendor-B5fJPoU1.js";import"./vendor-BE-_xUHH.js";const pe=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},Q=l=>({name:l.name,type:l.type,api_config:l.api_config?JSON.stringify(l.api_config):"",text_content:l.text_content,data_content:l.data_content,image_url:l.image_url,description:l.description,enabled:l.enabled,delay_seconds:l.delay_seconds,is_multi_spec:l.is_multi_spec,spec_name:l.spec_name,spec_value:l.spec_value}),me=async l=>{const n=await M(p=>O.GET("/api/v1/cards",{signal:p}),l);return te(n,["cards","data","items"]).map(pe)},he=async l=>M(n=>O.POST("/api/v1/cards",{body:Q(l),signal:n})),H=async(l,n)=>M(a=>O.PUT("/api/v1/cards/{card_id}",{params:{path:{card_id:String(l)}},body:Q(n),signal:a})),ue=async l=>M(n=>O.DELETE("/api/v1/cards/{card_id}",{params:{path:{card_id:String(l)}},signal:n})),be=async(l,n)=>{const a=new FormData;return a.append("file",l),M(p=>O.POST("/api/v1/cards/batch",{body:ee(a),signal:p}),n)},ge=async(l,n,a)=>M(p=>O.POST("/api/v1/cards/{card_id}/append-data",{params:{path:{card_id:String(l)}},body:{content:n},signal:p}),a),ye=(l,n,a)=>{const p=a.trim().toLocaleLowerCase();return l.filter(h=>(!n||h.type===n)&&(!p||h.name.toLocaleLowerCase().includes(p)))},Z=l=>l.split(`
|
||||
import{a as c,b as U,j as e}from"./react-vendor-Bf9ELcll.js";import{r as M,c as O,a as ee}from"./index-C6RECy_0.js";import{c as te}from"./contract-COFcZjyb.js";import{X as V,W as ae,J as z,Y as se,L as q,N as J,C as X,_ as le,$ as Y,a0 as K,a1 as ne,I as re,a2 as oe,V as ce,y as ie,P as de,o as xe}from"./icons-vendor-B5fJPoU1.js";import"./vendor-BE-_xUHH.js";const pe=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},Q=l=>({name:l.name,type:l.type,api_config:l.api_config?JSON.stringify(l.api_config):"",text_content:l.text_content,data_content:l.data_content,image_url:l.image_url,description:l.description,enabled:l.enabled,delay_seconds:l.delay_seconds,is_multi_spec:l.is_multi_spec,spec_name:l.spec_name,spec_value:l.spec_value}),me=async l=>{const n=await M(p=>O.GET("/api/v1/cards",{signal:p}),l);return te(n,["cards","data","items"]).map(pe)},he=async l=>M(n=>O.POST("/api/v1/cards",{body:Q(l),signal:n})),H=async(l,n)=>M(a=>O.PUT("/api/v1/cards/{card_id}",{params:{path:{card_id:String(l)}},body:Q(n),signal:a})),ue=async l=>M(n=>O.DELETE("/api/v1/cards/{card_id}",{params:{path:{card_id:String(l)}},signal:n})),be=async(l,n)=>{const a=new FormData;return a.append("file",l),M(p=>O.POST("/api/v1/cards/batch",{body:ee(a),signal:p}),n)},ge=async(l,n,a)=>M(p=>O.POST("/api/v1/cards/{card_id}/append-data",{params:{path:{card_id:String(l)}},body:{content:n},signal:p}),a),ye=(l,n,a)=>{const p=a.trim().toLocaleLowerCase();return l.filter(h=>(!n||h.type===n)&&(!p||h.name.toLocaleLowerCase().includes(p)))},Z=l=>l.split(`
|
||||
`).map(n=>n.trim()).filter(Boolean),fe=(l,n,a)=>!!(l&&Z(n).length>0&&!a),F=(l,n,a,p)=>l===n&&a===p,W=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),G=(l,n)=>l instanceof Error?l.message:n,je=({cards:l,loadCards:n})=>{const[a,p]=c.useState(!1),[h,_]=c.useState(!1),[f,j]=c.useState(null),[d,T]=c.useState({}),[i,y]=c.useState(W),[N,b]=c.useState(""),[r,x]=c.useState(""),s=c.useMemo(()=>l.filter(o=>o.type==="data"),[l]),u=c.useMemo(()=>ye(l,N,r),[l,r,N]),I=c.useCallback(o=>{var t,g,k,S,C;j(o),T({id:o.id,name:o.name||"",type:o.type||"text",api_url:((t=o.api_config)==null?void 0:t.url)||"",api_method:((g=o.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=o.api_config)==null?void 0:k.timeout)||10,api_headers:((S=o.api_config)==null?void 0:S.headers)||"",api_params:((C=o.api_config)==null?void 0:C.params)||"",text_content:o.text_content||"",data_content:o.data_content||"",image_url:o.image_url||"",delay_seconds:o.delay_seconds||0,description:o.description||"",enabled:o.enabled}),p(!0)},[]),L=c.useCallback(async()=>{var o,t,g,k,S,C,m,A;if(f){if(!((o=d.name)!=null&&o.trim())){alert("请输入卡密名称");return}if(!d.type){alert("请选择卡密类型");return}try{const w={name:d.name.trim(),type:d.type,description:(t=d.description)==null?void 0:t.trim(),delay_seconds:d.delay_seconds||0,enabled:d.enabled??!0};d.type==="api"?w.api_config={url:((g=d.api_url)==null?void 0:g.trim())||"",method:d.api_method||"GET",timeout:d.api_timeout||10,headers:((k=d.api_headers)==null?void 0:k.trim())||void 0,params:((S=d.api_params)==null?void 0:S.trim())||void 0}:d.type==="text"?w.text_content=((C=d.text_content)==null?void 0:C.trim())||"":d.type==="data"?w.data_content=((m=d.data_content)==null?void 0:m.trim())||"":d.type==="image"&&(w.image_url=((A=d.image_url)==null?void 0:A.trim())||""),await H(f.id,w),p(!1),await n()}catch(w){console.error("更新卡密失败:",w),alert(G(w,"更新失败,请重试"))}}},[d,n,f]),P=c.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await ue(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(G(t,"删除失败,请重试"))}},[n]),v=c.useCallback(async()=>{if(!i.name.trim()){alert("请输入卡密名称");return}if(!i.content.trim()){alert(i.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const o={name:i.name.trim(),type:i.type,description:i.description.trim(),enabled:i.enabled,delay_seconds:i.delay_seconds};i.type==="text"&&(o.text_content=i.content.trim()),i.type==="data"&&(o.data_content=i.content.trim()),i.type==="image"&&(o.image_url=i.content.trim()),i.type==="api"&&(o.api_config={url:i.content.trim(),method:i.api_method,timeout:i.api_timeout,headers:i.api_headers.trim()||void 0,params:i.api_params.trim()||void 0}),await he(o),_(!1),y(W()),await n()}catch(o){console.error("添加卡密失败:",o),alert(G(o,"添加失败,请重试"))}},[i,n]),B=c.useCallback(async o=>{try{await H(o.id,{...o,enabled:!o.enabled}),await n()}catch(t){console.error("切换状态失败:",t)}},[n]),R=c.useCallback(async o=>{try{await navigator.clipboard.writeText(String(o)),alert(`已复制卡密组ID:${o}`)}catch{prompt("复制卡密组ID",String(o))}},[]),D=c.useCallback(()=>{const g=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(m=>m.map(A=>`"${String(A).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{d as S,j as e,a as n}from"./react-vendor-Bf9ELcll.js";import{L as oe}from"./vendor-BE-_xUHH.js";import{B as pe}from"./audio-codec-mjVr_wwJ.js";import{L as $,al as de,am as me,q as ge,an as xe,ao as ue,M as z0,I as he,R as _e,ad as D0,k as be,ap as fe,t as W0,aq as je,ar as we,ai as J0,X as Ne}from"./icons-vendor-B5fJPoU1.js";import{g as U0,p as ye,b as Q0,m as V0,s as Ce,d as Oe,e as ve,f as ke,h as Z0}from"./index-BcKVxEYs.js";const F0="ydisks:chat-audio-play",Se=[6,10,15,8,17,12,7,16,11,6,14,9];function Re(r){const c=r.trim();if(typeof location>"u"||location.protocol!=="https:")return c;try{const a=new URL(c);return a.protocol==="http:"&&a.hostname.endsWith(".aliyuncs.com")&&(a.protocol="https:"),a.toString()}catch{return c}}function q0(r){const c=Number.isFinite(r)?Math.max(0,Math.floor(r)):0,a=Math.floor(c/60),i=c%60;return`${a}:${i.toString().padStart(2,"0")}`}function T0(r){window.dispatchEvent(new CustomEvent(F0,{detail:r}))}const Ee=({messageKey:r,src:c,outgoing:a,initialDuration:i=0})=>{const x=S.useRef(null),N=S.useRef(0),[d,R]=S.useState("idle"),[E,L]=S.useState(i),[W,q]=S.useState(0);S.useEffect(()=>(()=>{var u;N.current+=1,(u=x.current)==null||u.destroy(),x.current=null}),[c]),S.useEffect(()=>{L(Math.max(0,i))},[i]),S.useEffect(()=>{const u=b=>{const j=b.detail,y=x.current;j!==r&&(y!=null&&y.isPlaying())&&y.pause()};return window.addEventListener(F0,u),(()=>window.removeEventListener(F0,u))},[r]),S.useEffect(()=>{if(d!=="playing")return;const u=window.setInterval(()=>{const b=x.current;b&&q(b.getCurrentPosition())},100);return(()=>window.clearInterval(u))},[d]);const T=(u,b)=>{const j=()=>N.current===b&&x.current===u;u.onPlay(()=>{j()&&R("playing")}),u.onResume(()=>{j()&&R("playing")}),u.onPause(()=>{j()&&R("paused")}),u.onStop(()=>{j()&&(R("idle"),q(0))}),u.onEnded(()=>{j()&&(R("idle"),q(0))})},n0=async()=>{var j;const u=x.current;if(u!=null&&u.isPlaying()){u.pause();return}if(u!=null&&u.isPaused()){T0(r),u.resume();return}if(u!=null&&u.isInit()){T0(r),u.play();return}if(d==="loading")return;const b=N.current+1;N.current=b,R("loading"),q(0);try{const y=new pe;if(x.current=y,T(y,b),await y.initWithUrl(Re(c)),N.current!==b||x.current!==y){y.destroy();return}L(y.getDuration()||Math.max(0,i)),T0(r),y.play()}catch{if(N.current!==b)return;(j=x.current)==null||j.destroy(),x.current=null,R("error"),q(0)}},A=d==="playing"||d==="paused"?W:E,G=E>0?d==="playing"||d==="paused"?`${q0(A)} / ${q0(E)}`:q0(E):"--:--",D=d==="loading"?"正在解码":d==="playing"?"正在播放":d==="paused"?"已暂停":d==="error"?"加载失败,点击重试":"语音消息",k=d==="playing"?"暂停语音消息":d==="paused"?"继续播放语音消息":d==="error"?"重新加载语音消息":d==="loading"?"正在加载语音消息":"播放语音消息";return e.jsxs("div",{className:`flex h-11 min-w-56 items-center gap-2 rounded-2xl border px-2 shadow-sm ${a?"rounded-br-md border-sky-400 bg-sky-500 text-white":"rounded-bl-md border-slate-200 bg-white text-slate-800"}`,children:[e.jsx("button",{type:"button","aria-label":k,title:k,disabled:d==="loading",onClick:(()=>void n0()),className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-full transition focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-wait ${a?"bg-white text-sky-600 hover:bg-sky-50 focus-visible:ring-white":"bg-sky-50 text-sky-600 hover:bg-sky-100 focus-visible:ring-sky-400"}`,children:d==="loading"?e.jsx($,{className:"h-4 w-4 animate-spin"}):d==="playing"?e.jsx(de,{className:"h-4 w-4 fill-current"}):d==="error"?e.jsx(me,{className:"h-4 w-4"}):e.jsx(ge,{className:"ml-px h-4 w-4 fill-current"})}),e.jsxs("div",{className:"min-w-0 flex flex-1 items-center gap-2",children:[e.jsx("div",{className:"flex h-5 flex-1 items-center gap-0.5","aria-hidden":"true",children:Se.map((u,b)=>e.jsx("span",{className:`w-0.5 rounded-full ${d==="playing"?"animate-pulse":""} ${a?"bg-sky-100":d==="error"?"bg-red-300":"bg-sky-400"}`,style:{height:`${u}px`,animationDelay:`${b*45}ms`}},`${r}-${b}`))}),e.jsx("span",{className:`shrink-0 font-mono text-[11px] font-semibold tabular-nums ${a?"text-sky-100":d==="error"?"text-red-500":"text-slate-500"}`,children:G}),e.jsx("span",{className:"sr-only",children:D})]})]})},X0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png
Line truncated
|
||||
import{d as S,j as e,a as n}from"./react-vendor-Bf9ELcll.js";import{L as oe}from"./vendor-BE-_xUHH.js";import{B as pe}from"./audio-codec-mjVr_wwJ.js";import{L as $,al as de,am as me,q as ge,an as xe,ao as ue,M as z0,I as he,R as _e,ad as D0,k as be,ap as fe,t as W0,aq as je,ar as we,ai as J0,X as Ne}from"./icons-vendor-B5fJPoU1.js";import{g as U0,p as ye,b as Q0,m as V0,s as Ce,d as Oe,e as ve,f as ke,h as Z0}from"./index-C6RECy_0.js";const F0="ydisks:chat-audio-play",Se=[6,10,15,8,17,12,7,16,11,6,14,9];function Re(r){const c=r.trim();if(typeof location>"u"||location.protocol!=="https:")return c;try{const a=new URL(c);return a.protocol==="http:"&&a.hostname.endsWith(".aliyuncs.com")&&(a.protocol="https:"),a.toString()}catch{return c}}function q0(r){const c=Number.isFinite(r)?Math.max(0,Math.floor(r)):0,a=Math.floor(c/60),i=c%60;return`${a}:${i.toString().padStart(2,"0")}`}function T0(r){window.dispatchEvent(new CustomEvent(F0,{detail:r}))}const Ee=({messageKey:r,src:c,outgoing:a,initialDuration:i=0})=>{const x=S.useRef(null),N=S.useRef(0),[d,R]=S.useState("idle"),[E,L]=S.useState(i),[W,q]=S.useState(0);S.useEffect(()=>(()=>{var u;N.current+=1,(u=x.current)==null||u.destroy(),x.current=null}),[c]),S.useEffect(()=>{L(Math.max(0,i))},[i]),S.useEffect(()=>{const u=b=>{const j=b.detail,y=x.current;j!==r&&(y!=null&&y.isPlaying())&&y.pause()};return window.addEventListener(F0,u),(()=>window.removeEventListener(F0,u))},[r]),S.useEffect(()=>{if(d!=="playing")return;const u=window.setInterval(()=>{const b=x.current;b&&q(b.getCurrentPosition())},100);return(()=>window.clearInterval(u))},[d]);const T=(u,b)=>{const j=()=>N.current===b&&x.current===u;u.onPlay(()=>{j()&&R("playing")}),u.onResume(()=>{j()&&R("playing")}),u.onPause(()=>{j()&&R("paused")}),u.onStop(()=>{j()&&(R("idle"),q(0))}),u.onEnded(()=>{j()&&(R("idle"),q(0))})},n0=async()=>{var j;const u=x.current;if(u!=null&&u.isPlaying()){u.pause();return}if(u!=null&&u.isPaused()){T0(r),u.resume();return}if(u!=null&&u.isInit()){T0(r),u.play();return}if(d==="loading")return;const b=N.current+1;N.current=b,R("loading"),q(0);try{const y=new pe;if(x.current=y,T(y,b),await y.initWithUrl(Re(c)),N.current!==b||x.current!==y){y.destroy();return}L(y.getDuration()||Math.max(0,i)),T0(r),y.play()}catch{if(N.current!==b)return;(j=x.current)==null||j.destroy(),x.current=null,R("error"),q(0)}},A=d==="playing"||d==="paused"?W:E,G=E>0?d==="playing"||d==="paused"?`${q0(A)} / ${q0(E)}`:q0(E):"--:--",D=d==="loading"?"正在解码":d==="playing"?"正在播放":d==="paused"?"已暂停":d==="error"?"加载失败,点击重试":"语音消息",k=d==="playing"?"暂停语音消息":d==="paused"?"继续播放语音消息":d==="error"?"重新加载语音消息":d==="loading"?"正在加载语音消息":"播放语音消息";return e.jsxs("div",{className:`flex h-11 min-w-56 items-center gap-2 rounded-2xl border px-2 shadow-sm ${a?"rounded-br-md border-sky-400 bg-sky-500 text-white":"rounded-bl-md border-slate-200 bg-white text-slate-800"}`,children:[e.jsx("button",{type:"button","aria-label":k,title:k,disabled:d==="loading",onClick:(()=>void n0()),className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-full transition focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-wait ${a?"bg-white text-sky-600 hover:bg-sky-50 focus-visible:ring-white":"bg-sky-50 text-sky-600 hover:bg-sky-100 focus-visible:ring-sky-400"}`,children:d==="loading"?e.jsx($,{className:"h-4 w-4 animate-spin"}):d==="playing"?e.jsx(de,{className:"h-4 w-4 fill-current"}):d==="error"?e.jsx(me,{className:"h-4 w-4"}):e.jsx(ge,{className:"ml-px h-4 w-4 fill-current"})}),e.jsxs("div",{className:"min-w-0 flex flex-1 items-center gap-2",children:[e.jsx("div",{className:"flex h-5 flex-1 items-center gap-0.5","aria-hidden":"true",children:Se.map((u,b)=>e.jsx("span",{className:`w-0.5 rounded-full ${d==="playing"?"animate-pulse":""} ${a?"bg-sky-100":d==="error"?"bg-red-300":"bg-sky-400"}`,style:{height:`${u}px`,animationDelay:`${b*45}ms`}},`${r}-${b}`))}),e.jsx("span",{className:`shrink-0 font-mono text-[11px] font-semibold tabular-nums ${a?"text-sky-100":d==="error"?"text-red-500":"text-slate-500"}`,children:G}),e.jsx("span",{className:"sr-only",children:D})]})]})},X0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png
Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,a as c}from"./react-vendor-Bf9ELcll.js";import{f as ge}from"./dateTime-DDi7rqpW.js";import{j as xe,k as he,l as se,D as pe,c as be,P as fe,m as ae,E as ye,T as je}from"./icons-vendor-B5fJPoU1.js";import{R as q,B as ve,X as re,Y as ne,T as W,a as Ne,C as X,A as we,b as _e,c as ke,P as le,d as oe,L as De}from"./charts-vendor-DBu_rVrn.js";import{r as M,c as K}from"./index-BcKVxEYs.js";import{c as ue,o as Se}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.js";const F=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},J=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},H=(t,a)=>({startDate:F(J(t,-(a-1))),endDate:F(t)}),me=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?H(J(a,-1),1):H(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Ce=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=J(a,-1);return H(n,l)},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,$e=({chartData:t,selectedRangeLabel:a,totalAmount:s})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[a,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||s===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(xe,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(q,{width:"100%",height:"100%",children:e.jsxs(ve,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(re,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(ne,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(W,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(Ne,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(X,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(q,{width:"100%",height:"100%",children:e.jsxs(we,{data:t,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(re,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(ne,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(_e,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(W,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(ke,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),ie=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Re=async t=>M(a=>K.GET("/api/v1/analytics/dashboard",{signal:a}),t),Le=async(t,a)=>{const s=await M(n=>K.GET("/api/v1/items",{params:{query:{cookie_id:t}},signal:n}),a);return ue(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ce=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:F(n),end_date:F(l)}}else s=t;return M(l=>K.GET("/api/v1/analytics/orders",{params:{query:{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()}},signal:l}),a)},Te=async(t,a)=>{const s=await M(u=>K.GET("/api/v1/analytics/orders/valid",{params:{query:{...t,timezone_oLine truncated
|
||||
import{j as e,a as c}from"./react-vendor-Bf9ELcll.js";import{f as ge}from"./dateTime-DDi7rqpW.js";import{j as xe,k as he,l as se,D as pe,c as be,P as fe,m as ae,E as ye,T as je}from"./icons-vendor-B5fJPoU1.js";import{R as q,B as ve,X as re,Y as ne,T as W,a as Ne,C as X,A as we,b as _e,c as ke,P as le,d as oe,L as De}from"./charts-vendor-DBu_rVrn.js";import{r as M,c as K}from"./index-C6RECy_0.js";import{c as ue,o as Se}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.js";const F=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},J=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},H=(t,a)=>({startDate:F(J(t,-(a-1))),endDate:F(t)}),me=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?H(J(a,-1),1):H(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Ce=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=J(a,-1);return H(n,l)},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,$e=({chartData:t,selectedRangeLabel:a,totalAmount:s})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[a,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||s===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(xe,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(q,{width:"100%",height:"100%",children:e.jsxs(ve,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(re,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(ne,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(W,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(Ne,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(X,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(q,{width:"100%",height:"100%",children:e.jsxs(we,{data:t,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(re,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(ne,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(_e,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(W,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(ke,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),ie=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Re=async t=>M(a=>K.GET("/api/v1/analytics/dashboard",{signal:a}),t),Le=async(t,a)=>{const s=await M(n=>K.GET("/api/v1/items",{params:{query:{cookie_id:t}},signal:n}),a);return ue(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ce=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:F(n),end_date:F(l)}}else s=t;return M(l=>K.GET("/api/v1/analytics/orders",{params:{query:{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()}},signal:l}),a)},Te=async(t,a)=>{const s=await M(u=>K.GET("/api/v1/analytics/orders/valid",{params:{query:{...t,timezone_oLine truncated
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
import{j as e,a as r,b as we}from"./react-vendor-Bf9ELcll.js";import{r as B,c as q,a as Qe,A as gt}from"./index-BcKVxEYs.js";import{c as et}from"./contract-COFcZjyb.js";import{a3 as yt,U as $e,R as Se,N as De,a4 as Pe,a5 as _e,V as ft,y as jt,B as vt,a6 as Oe,a7 as Nt,a8 as wt,A as _t,d as kt,X as ye,o as Ct,a9 as Ue,I as ze}from"./icons-vendor-B5fJPoU1.js";import"./vendor-BE-_xUHH.js";const Ke="ydisks-amap-js-api",It="c9b68d4ce9a2a97f22a4a439404488ca";let fe=null;const St=()=>It,Pt=()=>window.AMap?Promise.resolve(window.AMap):fe||(fe=new Promise((s,a)=>{const n=document.getElementById(Ke),d=n||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(G)},f=()=>{window.AMap?(u(),s(window.AMap)):(u(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},G=window.setTimeout(()=>{u(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=f,d.id=Ke,d.async=!0,d.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(St())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,d.onerror=()=>{u(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},n||document.head.appendChild(d)}).catch(s=>{throw fe=null,s}),fe),ke=s=>Number.isFinite(s)&&s!==0,Bt=s=>{var u,f;const a=Number((u=s.location)==null?void 0:u.lng),n=Number((f=s.location)==null?void 0:f.lat),d={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:a,latitude:n,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!d.division_id||!d.province||!d.city||!d.poi_id||!d.poi_name||!ke(a)||!ke(n)||a<-180||a>180||n<-90||n>90?null:d},qt=async(s,a,n={})=>{if(!ke(s)||!ke(a)||s<-180||s>180||a<-90||a>90)throw new Error("经纬度无效");const d=await Pt();return new Promise((u,f)=>{var $,R;let G=!1;const k=Math.max(1,n.timeoutMs??1e4),M=F=>{var p;G||(G=!0,globalThis.clearTimeout(W),(p=n.signal)==null||p.removeEventListener("abort",I),F())},I=()=>M(()=>f(new DOMException("aborted","AbortError"))),W=globalThis.setTimeout(()=>M(()=>f(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if(($=n.signal)!=null&&$.aborted){I();return}(R=n.signal)==null||R.addEventListener("abort",I,{once:!0}),new d.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,a],1e3,(F,p)=>{var x;if(G)return;if(F!=="complete"){if(F==="no_data"){M(()=>u([]));return}M(()=>f(new Error("高德地图附近地址查询失败,请稍后重试")));return}const E=(((x=p==null?void 0:p.poiList)==null?void 0:x.pois)||[]).map(Bt).filter(j=>j!==null);M(()=>u(E))})})},Et=async s=>B(a=>q.GET("/api/v1/accounts/details",{signal:a}),s),Je=async s=>B(a=>q.GET("/api/v1/automation-rules",{signal:a}),s),Lt=(s,a,n)=>qt(s,a,n),Be=(s,a)=>{if(s instanceof gt)switch(s.code){case"stock_permission_missing":return"发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。";case"conflict":case"item_conflict":return"商品状态已发生变化,请刷新后重试。";case"external_result_unknown":case"manual_review_required":return"平台结果暂时无法确认,请先人工核对闲鱼状态,再决定是否重试。";case"retryable":case"temporarily_unavailable":return"平台暂时不可用,请稍后重试。";default:return s.message||a}if(s instanceof Error)return s.message;const n=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof n=="string"?n:a},qe=s=>s===!0||s===1||s==="1",Ze=async(s,a)=>{const n=await B(u=>q.GET("/api/v1/items",{params:{query:{cookie_id:s}},signal:u}),a);return et(n,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:qe(u.is_multi_spec),is_multi_qty_ship:qe(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:qe(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},At=async s=>B(a=>q.POST("/api/v1/items/get-all-from-account",{body:{cookie_id:s},signal:a})),Mt=async(s,a)=>B(n=>q.DELETE("/api/v1/items/{cookie_id}/{item_id}",{params:{path:{cookie_id:s,item_id:a}},signal:n})),Rt=async(s,a)=>B(n=>q.POST("/api/v1/items/{cookie_id}",{params:{path:{cookie_id:s}},body:a,signal:n})),Ft=async s=>{const a=new FormData;a.set("cookie_id",s.cookie_id),a.set("title",s.title),a.set("description",s.description),a.set("price",s.price),a.set("original_price",s.original_price||""),a.set("quantity",String(s.quantity)),a.set("postage_mode",s.postage_mode),a.set("postage",s.postage||""),s.location&&a.set("location",JSON.stringify(s.location));for(const n of s.images)a.append("images",n);return B(n=>q.POST("/api/v1/items/publish",{body:Qe(a),signal:n}))},Gt=async(s,a,n)=>B(d=>q.POST("/api/v1/items/publish-categories/recommend",{body:{cookie_id:s,keyword:a},signal:d}),n),Tt=async(s,a)=>{const n=new FormData;return n.set("file",s.file),s.imagesZip&&n.seLine truncated
|
||||
`),ee=new Blob(["\uFEFF"+A],{type:"text/csv;charset=utf-8"}),T=URL.createObjectURL(ee),P=document.createElement("a");P.href=T,P.download="批量铺货模板.csv",document.body.appendChild(P),P.click(),P.remove(),URL.revokeObjectURL(T)},[]),i=r.useCallback(()=>{y(o=>({...o,cookie_id:s||o.cookie_id})),p(!0)},[s]),h=r.useCallback(()=>{v(o=>({...o,cookie_id:s||o.cookie_id})),x(!0)},[s]),L=r.useCallback(async o=>{if(!(o?s:g.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");O();const A=new AbortController;Q.current=A;const ee=++K.current;S(!0);try{const T=await new Promise((ue,he)=>{const Ce=te=>ue(te),ie=te=>he(te);navigator.geolocation.getCurrentPosition(Ce,ie,{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})});if(A.signal.aborted||ee!==K.current)return;const P=await Lt(T.coords.longitude,T.coords.latitude,{signal:A.signal});if(A.signal.aborted||ee!==K.current)return;if(!P.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(G(P),k(P[0])):(H(P),z(P[0]))}catch(T){if(A.signal.aborted||ee!==K.current)return;if(typeof T=="object"&&T!==null&&"code"in T){const P=T;alert(P.code===P.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")}else alert(Be(T,"获取发货地失败"))}finally{ee===K.current&&(Q.current=null,S(!1))}},[O,g.cookie_id,s,k,G]);return{selectedAccount:s,setSelectedAccount:a,loading:M,publishing:W,showEditModal:$,setShowEditModal:R,showAddModal:F,setShowAddModal:p,showPublishModal:E,setShowPublishModal:x,locationLoading:j,publishLocations:Y,setPublishLocations:H,publishLocation:X,setPublishLocation:z,selectedItem:D,editForm:C,setEditForm:le,addForm:b,setAddForm:y,publishForm:g,setPublishForm:v,publishImagePreviews:m,handleSync:ae,handleEdit:de,handleSaveEdit:ne,handleDelete:xe,handleAddItem:me,handlePublishItem:ve,downloadPublishTemplate:l,openAddModal:i,openPublishModal:h,locateForPublish:L}},Ht=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},as=({onConfigureDelivery:s})=>{const[a,n]=r.useState([]),[d,u]=r.useState([]),[f,G]=r.useState([]),[k,M]=r.useState(""),[I,W]=r.useState(""),U=r.useRef(0),$=r.useRef(0),R=r.useCallback(async()=>{const t=++U.current,c=await Ze();t===U.current&&n(c)},[]),F=r.useCallback(async()=>{const t=++$.current,c=await Je();t===$.current&&u(c)},[]),p=Wt({selectedAccount:k,loadItems:R,loadShippingRules:F}),{showBatchModal:E,batchLoading:x,batchPhase:j,batchFile:S,setBatchFile:Y,batchImagesZip:H,setBatchImagesZip:X,batchCategoryKeyword:z,setBatchCategoryKeyword:D,batchCategoryLoading:Z,batchFallbackCategory:C,setBatchFallbackCategory:le,batchPreview:b,batchDetail:y,recentBatch:g,setRecentBatch:v,batchLocations:m,batchLocation:re,batchPublishIntervalSeconds:Q,setBatchPublishIntervalSeconds:K,setBatchLocations:O,setBatchLocation:ae,openBatchModal:de,handleRecommendBatchCategory:ne,openRecentBatchResult:xe,handlePreviewBatch:me,handleStartBatch:ve,handleCancelBatch:l,abandonBatchPreview:i,closeBatchModal:h,handleRetryBatchFailed:L}=p,o=Yt({selectedAccount:k,setSelectedAccount:M,setItems:n,loadItems:R,loadShippingRules:F,onConfigureDelivery:s,setBatchLocations:O,setBatchLocation:ae}),{loading:N,publishing:A,showEditModal:ee,setShowEditModal:T,showAddModal:P,setShowAddModal:ue,showPublishModal:he,setShowPublishModal:Ce,locationLoading:ie,publishLocations:te,setPublishLocations:st,publishLocation:at,setPublishLocation:Ee,selectedItem:Le,editForm:se,setEditForm:Ne,addForm:J,setAddForm:pe,publishForm:w,setPublishForm:V,publishImagePreviews:Ae,handleSync:lt,handleEdit:rt,handleSaveEdit:nt,handleDelete:it,handleAddItem:ct,handlePublishItem:ot,downloadPublishTemplate:dt,openAddModal:xt,openPublishModal:mt,locateForPublish:Me}=o;r.useEffect(()=>{const t=new AbortController,c=++U.current,_=++$.current;let ge=!0;return Promise.all([Et({signal:t.signal}),Ze(void 0,{signal:t.signal}),Je({signal:t.signal}),tt(20,{signal:t.signal})]).then(([ce,ht,pt,Te])=>{if(!ge||t.signal.aborted||c!==U.current||_!==$.current)return;G(ce),n(ht),u(pt);const bt=Te.find(Ie=>["running","canceling"].includes(Ie.status))||Te.find(Ie=>Ie.status!=="preview");v(bt||null)}).catch(ce=>{t.signal.aborted||console.error("加载商品配置失败:",ce)}),(()=>{ge=!1,t.abort()})},[]);const ut=t=>d.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id).length>0?d.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id):d.filter(c=>c.cookie_id===t.cookie_id&&!c.item_id),Re=r.useMemo(()=>new Map(f.map(t=>[t.id,t])),[f]),Fe=r.useMemo(()=>I?a.filter(t=>t.cookie_id===I):a,[I,a]),be=t=>{const c=Re.get(t),_=(c==null?void 0:c.remark)||(c==null?void 0:c.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Ge=t=>{const c=Re.get(t);return(c==null?void 0:c.remark)||(c==null?void 0:c.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{
Line truncated
|
||||
import{j as e,a as n,b as we}from"./react-vendor-Bf9ELcll.js";import{r as B,c as q,a as Qe,A as gt}from"./index-C6RECy_0.js";import{c as et}from"./contract-COFcZjyb.js";import{a3 as yt,U as $e,R as Se,N as De,a4 as Pe,a5 as _e,V as ft,y as jt,B as vt,a6 as Oe,a7 as Nt,a8 as wt,A as _t,d as kt,X as ye,o as Ct,a9 as Ue,I as ze}from"./icons-vendor-B5fJPoU1.js";import"./vendor-BE-_xUHH.js";const Ke="ydisks-amap-js-api",It="c9b68d4ce9a2a97f22a4a439404488ca";let fe=null;const St=()=>It,Pt=()=>window.AMap?Promise.resolve(window.AMap):fe||(fe=new Promise((s,a)=>{const r=document.getElementById(Ke),d=r||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(G)},f=()=>{window.AMap?(u(),s(window.AMap)):(u(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},G=window.setTimeout(()=>{u(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=f,d.id=Ke,d.async=!0,d.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(St())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,d.onerror=()=>{u(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},r||document.head.appendChild(d)}).catch(s=>{throw fe=null,s}),fe),ke=s=>Number.isFinite(s)&&s!==0,Bt=s=>{var u,f;const a=Number((u=s.location)==null?void 0:u.lng),r=Number((f=s.location)==null?void 0:f.lat),d={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:a,latitude:r,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!d.division_id||!d.province||!d.city||!d.poi_id||!d.poi_name||!ke(a)||!ke(r)||a<-180||a>180||r<-90||r>90?null:d},qt=async(s,a,r={})=>{if(!ke(s)||!ke(a)||s<-180||s>180||a<-90||a>90)throw new Error("经纬度无效");const d=await Pt();return new Promise((u,f)=>{var $,R;let G=!1;const k=Math.max(1,r.timeoutMs??1e4),M=F=>{var p;G||(G=!0,globalThis.clearTimeout(W),(p=r.signal)==null||p.removeEventListener("abort",I),F())},I=()=>M(()=>f(new DOMException("aborted","AbortError"))),W=globalThis.setTimeout(()=>M(()=>f(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if(($=r.signal)!=null&&$.aborted){I();return}(R=r.signal)==null||R.addEventListener("abort",I,{once:!0}),new d.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,a],1e3,(F,p)=>{var x;if(G)return;if(F!=="complete"){if(F==="no_data"){M(()=>u([]));return}M(()=>f(new Error("高德地图附近地址查询失败,请稍后重试")));return}const E=(((x=p==null?void 0:p.poiList)==null?void 0:x.pois)||[]).map(Bt).filter(j=>j!==null);M(()=>u(E))})})},Et=async s=>B(a=>q.GET("/api/v1/accounts/details",{signal:a}),s),Je=async s=>B(a=>q.GET("/api/v1/automation-rules",{signal:a}),s),Lt=(s,a,r)=>qt(s,a,r),Be=(s,a)=>{if(s instanceof gt)switch(s.code){case"stock_permission_missing":return"发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。";case"conflict":case"item_conflict":return"商品状态已发生变化,请刷新后重试。";case"external_result_unknown":case"manual_review_required":return"平台结果暂时无法确认,请先人工核对闲鱼状态,再决定是否重试。";case"retryable":case"temporarily_unavailable":return"平台暂时不可用,请稍后重试。";default:return s.message||a}if(s instanceof Error)return s.message;const r=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof r=="string"?r:a},qe=s=>s===!0||s===1||s==="1",Ze=async(s,a)=>{const r=await B(u=>q.GET("/api/v1/items",{params:{query:{cookie_id:s}},signal:u}),a);return et(r,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:qe(u.is_multi_spec),is_multi_qty_ship:qe(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:qe(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},At=async s=>B(a=>q.POST("/api/v1/items/get-all-from-account",{body:{cookie_id:s},signal:a})),Mt=async(s,a)=>B(r=>q.DELETE("/api/v1/items/{cookie_id}/{item_id}",{params:{path:{cookie_id:s,item_id:a}},signal:r})),Rt=async(s,a)=>B(r=>q.POST("/api/v1/items/{cookie_id}",{params:{path:{cookie_id:s}},body:a,signal:r})),Ft=async s=>{const a=new FormData;a.set("cookie_id",s.cookie_id),a.set("title",s.title),a.set("description",s.description),a.set("price",s.price),a.set("original_price",s.original_price||""),a.set("quantity",String(s.quantity)),a.set("postage_mode",s.postage_mode),a.set("postage",s.postage||""),s.location&&a.set("location",JSON.stringify(s.location));for(const r of s.images)a.append("images",r);return B(r=>q.POST("/api/v1/items/publish",{body:Qe(a),signal:r}))},Gt=async(s,a,r)=>B(d=>q.POST("/api/v1/items/publish-categories/recommend",{body:{cookie_id:s,keyword:a},signal:d}),r),Tt=async(s,a)=>{const r=new FormData;return r.set("file",s.file),s.imagesZip&&r.seLine truncated
|
||||
`),ee=new Blob(["\uFEFF"+A],{type:"text/csv;charset=utf-8"}),T=URL.createObjectURL(ee),P=document.createElement("a");P.href=T,P.download="批量铺货模板.csv",document.body.appendChild(P),P.click(),P.remove(),URL.revokeObjectURL(T)},[]),i=n.useCallback(()=>{y(c=>({...c,cookie_id:s||c.cookie_id})),p(!0)},[s]),h=n.useCallback(()=>{v(c=>({...c,cookie_id:s||c.cookie_id})),x(!0)},[s]),L=n.useCallback(async c=>{if(!(c?s:g.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");O();const A=new AbortController;Q.current=A;const ee=++K.current;S(!0);try{const T=await new Promise((ue,he)=>{const Ce=te=>ue(te),ie=te=>he(te);navigator.geolocation.getCurrentPosition(Ce,ie,{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})});if(A.signal.aborted||ee!==K.current)return;const P=await Lt(T.coords.longitude,T.coords.latitude,{signal:A.signal});if(A.signal.aborted||ee!==K.current)return;if(!P.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");c?(G(P),k(P[0])):(H(P),z(P[0]))}catch(T){if(A.signal.aborted||ee!==K.current)return;if(typeof T=="object"&&T!==null&&"code"in T){const P=T;alert(P.code===P.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")}else alert(Be(T,"获取发货地失败"))}finally{ee===K.current&&(Q.current=null,S(!1))}},[O,g.cookie_id,s,k,G]);return{selectedAccount:s,setSelectedAccount:a,loading:M,publishing:W,showEditModal:$,setShowEditModal:R,showAddModal:F,setShowAddModal:p,showPublishModal:E,setShowPublishModal:x,locationLoading:j,publishLocations:Y,setPublishLocations:H,publishLocation:X,setPublishLocation:z,selectedItem:D,editForm:C,setEditForm:le,addForm:b,setAddForm:y,publishForm:g,setPublishForm:v,publishImagePreviews:m,handleSync:ae,handleEdit:de,handleSaveEdit:ne,handleDelete:xe,handleAddItem:me,handlePublishItem:ve,downloadPublishTemplate:l,openAddModal:i,openPublishModal:h,locateForPublish:L}},Xt=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},ls=({onConfigureDelivery:s})=>{const[a,r]=n.useState([]),[d,u]=n.useState([]),[f,G]=n.useState([]),[k,M]=n.useState(""),[I,W]=n.useState(""),U=n.useRef(0),$=n.useRef(0),R=n.useCallback(async()=>{const t=++U.current,o=await Ze();t===U.current&&r(o)},[]),F=n.useCallback(async()=>{const t=++$.current,o=await Je();t===$.current&&u(o)},[]),p=Yt({selectedAccount:k,loadItems:R,loadShippingRules:F}),{showBatchModal:E,batchLoading:x,batchPhase:j,batchFile:S,setBatchFile:Y,batchImagesZip:H,setBatchImagesZip:X,batchCategoryKeyword:z,setBatchCategoryKeyword:D,batchCategoryLoading:Z,batchFallbackCategory:C,setBatchFallbackCategory:le,batchPreview:b,batchDetail:y,recentBatch:g,setRecentBatch:v,batchLocations:m,batchLocation:re,batchPublishIntervalSeconds:Q,setBatchPublishIntervalSeconds:K,setBatchLocations:O,setBatchLocation:ae,openBatchModal:de,handleRecommendBatchCategory:ne,openRecentBatchResult:xe,handlePreviewBatch:me,handleStartBatch:ve,handleCancelBatch:l,abandonBatchPreview:i,closeBatchModal:h,handleRetryBatchFailed:L}=p,c=Ht({selectedAccount:k,setSelectedAccount:M,setItems:r,loadItems:R,loadShippingRules:F,onConfigureDelivery:s,setBatchLocations:O,setBatchLocation:ae}),{loading:N,publishing:A,showEditModal:ee,setShowEditModal:T,showAddModal:P,setShowAddModal:ue,showPublishModal:he,setShowPublishModal:Ce,locationLoading:ie,publishLocations:te,setPublishLocations:st,publishLocation:at,setPublishLocation:Ee,selectedItem:Le,editForm:se,setEditForm:Ne,addForm:J,setAddForm:pe,publishForm:w,setPublishForm:V,publishImagePreviews:Ae,handleSync:lt,handleEdit:rt,handleSaveEdit:nt,handleDelete:it,handleAddItem:ct,handlePublishItem:ot,downloadPublishTemplate:dt,openAddModal:xt,openPublishModal:mt,locateForPublish:Me}=c;n.useEffect(()=>{const t=new AbortController,o=++U.current,_=++$.current;let ge=!0;return Promise.all([Et({signal:t.signal}),Ze(void 0,{signal:t.signal}),Je({signal:t.signal}),tt(20,{signal:t.signal})]).then(([ce,ht,pt,Te])=>{if(!ge||t.signal.aborted||o!==U.current||_!==$.current)return;G(ce),r(ht),u(pt);const bt=Te.find(Ie=>["running","canceling"].includes(Ie.status))||Te.find(Ie=>Ie.status!=="preview");v(bt||null)}).catch(ce=>{t.signal.aborted||console.error("加载商品配置失败:",ce)}),(()=>{ge=!1,t.abort()})},[]);const ut=t=>d.filter(o=>o.cookie_id===t.cookie_id&&o.item_id===t.item_id).length>0?d.filter(o=>o.cookie_id===t.cookie_id&&o.item_id===t.item_id):d.filter(o=>o.cookie_id===t.cookie_id&&!o.item_id),Re=n.useMemo(()=>new Map(f.map(t=>[t.id,t])),[f]),Fe=n.useMemo(()=>I?a.filter(t=>t.cookie_id===I):a,[I,a]),be=t=>{const o=Re.get(t),_=(o==null?void 0:o.remark)||(o==null?void 0:o.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Ge=t=>{const o=Re.get(t);return(o==null?void 0:o.remark)||(o==null?void 0:o.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{
Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,b as _e,a as d}from"./react-vendor-Bf9ELcll.js";import{aj as te,ai as ae,ak as je,u as Q,e as I,L as z,w as Ne,y as ve,t as V,X as ne,z as re,F as le,o as ke,R as we,N as Se}from"./icons-vendor-B5fJPoU1.js";import{r as R,c as B}from"./index-BcKVxEYs.js";import"./vendor-BE-_xUHH.js";const Y=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],H=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},oe=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=Y.some(r=>String(s[r]??"").trim()!=="");return{...s,use_custom_smtp:t?H(s.use_custom_smtp,!1):a}},ie=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const r of Y)String(a[r]??"").trim()===""&&t[r]!==void 0&&(a[r]=t[r]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=H(a.smtp_use_tls,!0),a.smtp_use_ssl=H(a.smtp_use_ssl,!1),a},ce=s=>{const t=oe(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const r of Y)a[r]=t[r];return a},F={bark:{label:"Bark",icon:I,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:je,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:ae,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的Line truncated
|
||||
import{j as e,b as _e,a as d}from"./react-vendor-Bf9ELcll.js";import{aj as te,ai as ae,ak as je,u as Q,e as I,L as z,w as Ne,y as ve,t as V,X as ne,z as re,F as le,o as ke,R as we,N as Se}from"./icons-vendor-B5fJPoU1.js";import{r as R,c as B}from"./index-C6RECy_0.js";import"./vendor-BE-_xUHH.js";const Y=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],H=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},oe=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=Y.some(r=>String(s[r]??"").trim()!=="");return{...s,use_custom_smtp:t?H(s.use_custom_smtp,!1):a}},ie=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const r of Y)String(a[r]??"").trim()===""&&t[r]!==void 0&&(a[r]=t[r]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=H(a.smtp_use_tls,!0),a.smtp_use_ssl=H(a.smtp_use_ssl,!1),a},ce=s=>{const t=oe(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const r of Y)a[r]=t[r];return a},F={bark:{label:"Bark",icon:I,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:je,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:ae,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,b as H,a as r}from"./react-vendor-Bf9ELcll.js";import{f as ee}from"./dateTime-DDi7rqpW.js";import{U as ne,I as ie,X as K,J as oe,R as Y,N as ce,O as se,m as te,E as de,F as xe,V as me,y as ue,h as he,g as pe,o as ge}from"./icons-vendor-B5fJPoU1.js";import{r as O,c as M,a as be}from"./index-BcKVxEYs.js";import{o as ye,c as fe}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.js";const je=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],ve=s=>{const t=typeof s=="object"&&s!==null?s:{},a=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:a.map(Ne)}},Ne=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},we=s=>(s==null?void 0:s.results.filter(_e))||[],_e=s=>!s.success,ke=(s,t)=>s!==null&&!t,Ce=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},z=(s,t)=>s===t,Se=(s,t)=>s instanceof Error&&s.message?s.message:t,Ee=({filter:s,onFilterChange:t,accountFilter:a,onAccountFilterChange:u,accounts:h,accountName:x,searchText:p,onSearchChange:f})=>{const b=i=>t(i.currentTarget.dataset.status||"all"),y=i=>u(i.target.value),j=i=>f(i.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:je.map(i=>e.jsx("button",{"data-status":i.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===i.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:i.label},i.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ne,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:y,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),h.map(i=>e.jsx("option",{value:i.id,children:x(i.id)},i.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(ie,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:p,onChange:j,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const t=x=>{var p;s.setImportFile(((p=x.target.files)==null?void 0:p[0])||null)},a=()=>s.closeImportModal(),u=()=>void s.handleImportOrders(),h=()=>void s.handleRetryImport();return s.showImportModal?H.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(K,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:h,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 "Line truncated
|
||||
import{j as e,b as H,a as r}from"./react-vendor-Bf9ELcll.js";import{f as ee}from"./dateTime-DDi7rqpW.js";import{U as ne,I as ie,X as K,J as oe,R as Y,N as ce,O as se,m as te,E as de,F as xe,V as me,y as ue,h as he,g as pe,o as ge}from"./icons-vendor-B5fJPoU1.js";import{r as O,c as M,a as be}from"./index-C6RECy_0.js";import{o as ye,c as fe}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.js";const je=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],ve=s=>{const t=typeof s=="object"&&s!==null?s:{},a=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:a.map(Ne)}},Ne=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},we=s=>(s==null?void 0:s.results.filter(_e))||[],_e=s=>!s.success,ke=(s,t)=>s!==null&&!t,Ce=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},z=(s,t)=>s===t,Se=(s,t)=>s instanceof Error&&s.message?s.message:t,Ee=({filter:s,onFilterChange:t,accountFilter:a,onAccountFilterChange:u,accounts:h,accountName:x,searchText:p,onSearchChange:f})=>{const b=i=>t(i.currentTarget.dataset.status||"all"),y=i=>u(i.target.value),j=i=>f(i.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:je.map(i=>e.jsx("button",{"data-status":i.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===i.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:i.label},i.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ne,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:y,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),h.map(i=>e.jsx("option",{value:i.id,children:x(i.id)},i.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(ie,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:p,onChange:j,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const t=x=>{var p;s.setImportFile(((p=x.target.files)==null?void 0:p[0])||null)},a=()=>s.closeImportModal(),u=()=>void s.handleImportOrders(),h=()=>void s.handleRetryImport();return s.showImportModal?H.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(K,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:h,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 "Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,a as d,b as Oe}from"./react-vendor-Bf9ELcll.js";import{k as We,ae as ut,af as St,m as Rt,ag as pt,R as Ge,N as rt,Z as lt,u as At,n as nt,I as Pt,a1 as Tt,X as Ae,V as qe,y as Pe,h as Mt,g as $t,a6 as Et,ah as Lt,o as it,ai as It}from"./icons-vendor-B5fJPoU1.js";import{r as N,c as w}from"./index-BcKVxEYs.js";import{o as $e,c as Ze}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.js";const Ve=(t,s)=>t.allowed_resolutions.includes(s),Dt=(t,s)=>({runs:t.runs.filter(l=>!s||l.cookie_id===s),pending_tasks:t.pending_tasks.filter(l=>!s||l.cookie_id===s)}),Ft=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",zt=({runs:t,pendingTasks:s,onResolveRun:l,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(We,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Ft(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ve(r,"continue")&&e.jsx("button",{onClick:(()=>l(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ve(r,"retry")&&e.jsx("button",{onClick:(()=>l(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ve(r,"cancel")&&e.jsx("button",{onClick:(()=>l(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),s.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Ot=async t=>N(s=>w.GET("/api/v1/accounts/details",{signal:s}),t),gt=async t=>N(s=>w.GET("/api/v1/cards",{signal:s}),t),bt=async(t,s)=>N(l=>w.GET("/api/v1/items",{params:{query:{cookie_id:t}},signal:l}),s),ht=t=>t.map(s=>{var l,u;return{id:String(s.id),name:s.name||"",trigger_type:s.trigger_type||"order_paid",item_keyword:s.item_title||s.item_id||"",cookie_id:s.cookie_id||"",item_id:s.item_id||"",item_title:s.item_title||"",card_group_id:Number(((l=(s.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:l.card_id)||0),card_group_name:((u=(s.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:s.priority||100,enabled:s.enabled||!1,config_json:s.config_json||"{}",actions:(s.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(s.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let h={};try{h=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:h.spec_name||"",spec_value:h.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:h.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Gt=async()=>{const t=await N(l=>w.GET("/api/v1/automation-rules",{signal:l})),s=Ze(Line truncated
|
||||
import{j as e,a as d,b as Oe}from"./react-vendor-Bf9ELcll.js";import{k as We,ae as ut,af as St,m as Rt,ag as pt,R as Ge,N as rt,Z as lt,u as At,n as nt,I as Pt,a1 as Tt,X as Ae,V as qe,y as Pe,h as Mt,g as $t,a6 as Et,ah as Lt,o as it,ai as It}from"./icons-vendor-B5fJPoU1.js";import{r as N,c as w}from"./index-C6RECy_0.js";import{o as $e,c as Ze}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.js";const Ve=(t,s)=>t.allowed_resolutions.includes(s),Dt=(t,s)=>({runs:t.runs.filter(l=>!s||l.cookie_id===s),pending_tasks:t.pending_tasks.filter(l=>!s||l.cookie_id===s)}),Ft=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",zt=({runs:t,pendingTasks:s,onResolveRun:l,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(We,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Ft(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ve(r,"continue")&&e.jsx("button",{onClick:(()=>l(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ve(r,"retry")&&e.jsx("button",{onClick:(()=>l(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ve(r,"cancel")&&e.jsx("button",{onClick:(()=>l(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),s.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Ot=async t=>N(s=>w.GET("/api/v1/accounts/details",{signal:s}),t),gt=async t=>N(s=>w.GET("/api/v1/cards",{signal:s}),t),bt=async(t,s)=>N(l=>w.GET("/api/v1/items",{params:{query:{cookie_id:t}},signal:l}),s),ht=t=>t.map(s=>{var l,u;return{id:String(s.id),name:s.name||"",trigger_type:s.trigger_type||"order_paid",item_keyword:s.item_title||s.item_id||"",cookie_id:s.cookie_id||"",item_id:s.item_id||"",item_title:s.item_title||"",card_group_id:Number(((l=(s.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:l.card_id)||0),card_group_name:((u=(s.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:s.priority||100,enabled:s.enabled||!1,config_json:s.config_json||"{}",actions:(s.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(s.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let h={};try{h=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:h.spec_name||"",spec_value:h.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:h.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Gt=async()=>{const t=await N(l=>w.GET("/api/v1/automation-rules",{signal:l})),s=Ze(Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{a as r,j as e}from"./react-vendor-Bf9ELcll.js";import{r as M,c as q}from"./index-BcKVxEYs.js";import{f as xe,R as ae,aa as ue,r as pe,z as T,F as D,ab as me,t as he,S as re,ac as le,ad as ge,o as ye}from"./icons-vendor-B5fJPoU1.js";import"./vendor-BE-_xUHH.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",fe=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],be=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),we=s=>{if("values"in s||"secrets"in s)return s;const a={},n={};for(const[d,x]of Object.entries(s))if(x!=null){if(oe.has(d)){n[d]=x===""?{action:"clear"}:{action:"replace",value:String(x)};continue}(typeof x=="string"||typeof x=="number"||typeof x=="boolean")&&(a[d]=x)}return Object.keys(n).length>0?{values:a,secrets:n}:a},je=s=>{const a={...s};for(const n of oe){const d=`${n}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const n=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(n)?n:10}return a},ve=async(s,a)=>M(n=>q.PUT("/api/v1/session/credentials",{body:s,signal:n}),a),_e=async s=>{const a=await M(n=>q.GET("/api/v1/settings/system",{signal:n}),s);return je(a)},Ne=async(s,a)=>M(n=>q.PUT("/api/v1/settings/system",{body:we(s),signal:n}),a),Se=async(s,a="",n)=>{const d=await M(x=>q.POST("/api/v1/settings/ai-models",{body:{base_url:s,api_key:a},signal:x}),n);return Array.isArray(d.models)?d.models:[]},ke=async s=>M(a=>q.GET("/api/v1/session",{signal:a}),s),Ce=s=>Object.fromEntries(Object.entries(s).filter(([a,n])=>!be.has(a)&&n!==void 0&&n!==null)),Ee=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,n)=>s===a&&!n.aborted,K=s=>s instanceof Error&&s.message==="请求已取消",U=(s,a)=>s instanceof Error?s.message:a,Ae=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),$=(s,a)=>({type:s,text:a}),Ie=()=>{const[s,a]=r.useState(null),[n,d]=r.useState(!1),[x,m]=r.useState(""),[S,A]=r.useState(!1),[R,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[P,u]=r.useState(""),[z,v]=r.useState(!1),[G,L]=r.useState(!1),[F,p]=r.useState(!1),[b,V]=r.useState(!1),[Y,J]=r.useState(!1),[W,_]=r.useState(!1),[O,y]=r.useState(null),[t,ee]=r.useState(()=>Ae()),[ce,B]=r.useState("idle"),se=r.useRef(null),te=r.useRef(null),h=r.useRef(0),H=r.useRef(null);te.current=s;const E=r.useCallback(()=>{var c;(c=H.current)==null||c.abort();const o=new AbortController;return H.current=o,h.current+=1,{controller:o,sequence:h.current}},[]),Q=r.useCallback(async(o,c=!1,l)=>{const i=o||te.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),u("");try{const N=await Se(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Z=>Z&&{...Z,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||K(N))return;w([]),v(!1),u(U(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),X=r.useCallback(()=>{const{controller:o,sequence:c}=E();d(!0),B("loading"),m(""),Promise.all([_e({signal:o.signal}),ke({signal:o.signal})]).then(([l,i])=>{f(h.current,c,o.signal)&&(a(l),i.username&&ee(g=>({...g,new_username:i.username||""})),Q(l,!1,o.signal),B("success"))}).catch(l=>{!f(h.current,c,o.signal)||K(l)||(a(null),m(U(l,"加载配置失败")),B("error"))}).finally(()=>{f(h.current,c,o.signal)&&d(!1)})},[E,Q]);r.useEffect(()=>(X(),(()=>{var o;return(o=H.current)==null?void 0:o.abort()})),[X]),r.useEffect(()=>{const o=c=>{var l;(l=se.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",o),(()=>document.removeEventListener("mousedown",o))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:o,sequence:c}=E();A(!0),k("");try{if(await Ne(Ce(s),{signal:o.signal}),!f(h.current,c,o.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(h.current,c,o.signal)||K(l))return;k(U(l,"保存配置失败"))}finally{f(h.current,c,o.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async o=>{o.preventDefault(),y(null);const c=Ee(t);if(c){y($("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await ve({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(h.currentLine truncated
|
||||
import{a as r,j as e}from"./react-vendor-Bf9ELcll.js";import{r as M,c as q}from"./index-C6RECy_0.js";import{f as xe,R as ae,aa as ue,r as pe,z as T,F as D,ab as me,t as he,S as re,ac as le,ad as ge,o as ye}from"./icons-vendor-B5fJPoU1.js";import"./vendor-BE-_xUHH.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",fe=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],be=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),we=s=>{if("values"in s||"secrets"in s)return s;const a={},n={};for(const[d,x]of Object.entries(s))if(x!=null){if(oe.has(d)){n[d]=x===""?{action:"clear"}:{action:"replace",value:String(x)};continue}(typeof x=="string"||typeof x=="number"||typeof x=="boolean")&&(a[d]=x)}return Object.keys(n).length>0?{values:a,secrets:n}:a},je=s=>{const a={...s};for(const n of oe){const d=`${n}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const n=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(n)?n:10}return a},ve=async(s,a)=>M(n=>q.PUT("/api/v1/session/credentials",{body:s,signal:n}),a),_e=async s=>{const a=await M(n=>q.GET("/api/v1/settings/system",{signal:n}),s);return je(a)},Ne=async(s,a)=>M(n=>q.PUT("/api/v1/settings/system",{body:we(s),signal:n}),a),Se=async(s,a="",n)=>{const d=await M(x=>q.POST("/api/v1/settings/ai-models",{body:{base_url:s,api_key:a},signal:x}),n);return Array.isArray(d.models)?d.models:[]},ke=async s=>M(a=>q.GET("/api/v1/session",{signal:a}),s),Ce=s=>Object.fromEntries(Object.entries(s).filter(([a,n])=>!be.has(a)&&n!==void 0&&n!==null)),Ee=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,n)=>s===a&&!n.aborted,K=s=>s instanceof Error&&s.message==="请求已取消",U=(s,a)=>s instanceof Error?s.message:a,Ae=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),$=(s,a)=>({type:s,text:a}),Ie=()=>{const[s,a]=r.useState(null),[n,d]=r.useState(!1),[x,m]=r.useState(""),[S,A]=r.useState(!1),[R,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[P,u]=r.useState(""),[z,v]=r.useState(!1),[G,L]=r.useState(!1),[F,p]=r.useState(!1),[b,V]=r.useState(!1),[Y,J]=r.useState(!1),[W,_]=r.useState(!1),[O,y]=r.useState(null),[t,ee]=r.useState(()=>Ae()),[ce,B]=r.useState("idle"),se=r.useRef(null),te=r.useRef(null),h=r.useRef(0),H=r.useRef(null);te.current=s;const E=r.useCallback(()=>{var c;(c=H.current)==null||c.abort();const o=new AbortController;return H.current=o,h.current+=1,{controller:o,sequence:h.current}},[]),Q=r.useCallback(async(o,c=!1,l)=>{const i=o||te.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),u("");try{const N=await Se(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Z=>Z&&{...Z,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||K(N))return;w([]),v(!1),u(U(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),X=r.useCallback(()=>{const{controller:o,sequence:c}=E();d(!0),B("loading"),m(""),Promise.all([_e({signal:o.signal}),ke({signal:o.signal})]).then(([l,i])=>{f(h.current,c,o.signal)&&(a(l),i.username&&ee(g=>({...g,new_username:i.username||""})),Q(l,!1,o.signal),B("success"))}).catch(l=>{!f(h.current,c,o.signal)||K(l)||(a(null),m(U(l,"加载配置失败")),B("error"))}).finally(()=>{f(h.current,c,o.signal)&&d(!1)})},[E,Q]);r.useEffect(()=>(X(),(()=>{var o;return(o=H.current)==null?void 0:o.abort()})),[X]),r.useEffect(()=>{const o=c=>{var l;(l=se.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",o),(()=>document.removeEventListener("mousedown",o))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:o,sequence:c}=E();A(!0),k("");try{if(await Ne(Ce(s),{signal:o.signal}),!f(h.current,c,o.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(h.current,c,o.signal)||K(l))return;k(U(l,"保存配置失败"))}finally{f(h.current,c,o.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async o=>{o.preventDefault(),y(null);const c=Ee(t);if(c){y($("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await ve({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(h.currentLine truncated
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-nm_Ta7yG.js","assets/react-vendor-Bf9ELcll.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-B5fJPoU1.js","assets/charts-vendor-DBu_rVrn.js","assets/vendor-BE-_xUHH.js","assets/vendor-DUblxfbA.css","assets/contract-COFcZjyb.js","assets/AccountList-ClEQWLWq.js","assets/OrderList-CTwm_EVa.js","assets/CardList-Ptkqaql3.js","assets/ItemList-nhrE5KKq.js","assets/Settings-DasfRIJS.js","assets/Rules-4R6_G6FE.js","assets/Notifications-BwTLeimZ.js","assets/Chat-CXgshIQ-.js","assets/audio-codec-mjVr_wwJ.js"])))=>i.map(i=>d[i]);
|
||||
import{d as P,j as t,a as l,e as K}from"./react-vendor-Bf9ELcll.js";import{o as W}from"./vendor-BE-_xUHH.js";import{L as z,a as I,S as J,U as Q,A as X,b as ee,c as te,M as se,C as ne,B as re,d as ae,Z as oe,e as ie,f as ce,G as R,g as le,h as de,i as ue}from"./icons-vendor-B5fJPoU1.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))c(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&c(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function c(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class he extends P.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:t.jsxs("section",{className:"max-w-md text-center",children:[t.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),t.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}let S=!1;class O extends Error{constructor(n,s){super(pe(s,n)),this.name="ApiError",this.status=n,this.code=N(s)?s.code:`http_${n}`,this.requestId=N(s)?s.request_id:void 0,this.request_id=this.requestId,this.details=N(s)?s.details:void 0,this.payload=s}}const me=()=>{S||typeof window>"u"||(S=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{S=!1}))},fe=(e,n)=>{const s=new AbortController,c=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?c():e==null||e.addEventListener("abort",c,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),e==null||e.removeEventListener("abort",c)}}},N=e=>{if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.code=="string"&&typeof n.message=="string"},pe=(e,n)=>typeof e=="string"?e:N(e)?e.message:`请求失败: ${n}`,xe=3e4,ge=(e,n)=>fetch(e,{...n,credentials:"include"}),be=typeof location>"u"?"http://localhost":location.origin,v=W({baseUrl:be,fetch:ge});function nt(e){return e}async function w(e,n={}){var c;const s=fe(n.signal,n.timeoutMs??xe);try{const r=await e(s.signal);if(r.response.status===401&&!n.skipAuthLogout&&me(),r.error!==void 0)throw new O(r.response.status,r.error);if(r.data===void 0)throw new O(r.response.status,void 0);return r.data}catch(r){throw s.signal.aborted?new Error((c=n.signal)!=null&&c.aborted?"请求已取消":"请求超时,请稍后重试"):r}finally{s.cleanup()}}const ve=async e=>{const n=await w(s=>v.POST("/api/v1/session/login",{body:e,signal:s}),{skipAuthLogout:!0});return{...n,token:n.token??void 0}},we=async e=>{const n=await w(s=>v.POST("/api/v1/session/initialize",{body:{password:e},signal:s}),{skipAuthLogout:!0});return{...n,token:n.token??void 0}},ye=async e=>w(n=>v.GET("/api/v1/session",{signal:n}),e),Le=async()=>({success:!0,message:(await w(n=>v.POST("/api/v1/session/logout",{body:{},signal:n}))).message}),U=l.createContext(void 0),je=({children:e})=>{const[n,s]=l.useState(!1),[c,r]=l.useState(!1),[i,a]=l.useState(!0),[o,u]=l.useState(!1),d=()=>{s(!1),r(!1)};l.useEffect(()=>{const x=new AbortController;let p=!0;ye({signal:x.signal}).then(b=>{if(p){if((b==null?void 0:b.initialized)===!1){u(!0),d();return}u(!1),b!=null&&b.authenticated?(s(!0),r(b.is_admin===!0)):d()}}).catch(b=>{!p||b instanceof DOMException&&b.name==="AbortError"||(u(!1),d())}).finally(()=>{p&&a(!1)});const h=()=>d();return window.addEventListener("auth:logout",h),(()=>{p=!1,x.abort(),window.removeEventListener("auth:logout",h)})},[]);const m=async x=>{const p=await ve(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},g=async x=>{const p=await we(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},f=async()=>{try{await Le()}finally{d()}};return t.jsx(U.Provider,{value:{checkingAuth:i,isLoggedIn:n,isAdmin:c,needsInit:o,signIn:m,initialize:g,signOut:f},children:e})},B=()=>{const e=l.useContext(U);if(!e)throw new Error("useSession 必须在 SessionProvider 内使用");return e},q="ydisks.sidebar.v1",Ce=()=>{try{return window.localStorage.getItem(q)==="collapsed"}catch{return!1}},_e=e=>{try{window.localStorage.setItem(q,e?"collapsed":"expanded")}catch{}},Ne=({className:e="w-full h-full text-white"})=>t.jsx("svg",{className:e,viewBox:"0 0 256 256","aria-hidden":"true",children:t.jsx("g",{stroke:"nLine truncated
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-DhFdaJwB.js","assets/react-vendor-Bf9ELcll.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-B5fJPoU1.js","assets/charts-vendor-DBu_rVrn.js","assets/vendor-BE-_xUHH.js","assets/vendor-DUblxfbA.css","assets/contract-COFcZjyb.js","assets/AccountList-C1r-CuCX.js","assets/OrderList-KOW-fFIJ.js","assets/CardList-BbF66c_P.js","assets/ItemList-C1pjlQfG.js","assets/Settings-aZQUe0t0.js","assets/Rules-CacQ324l.js","assets/Notifications-CccTJna_.js","assets/Chat-DJNDDkT1.js","assets/audio-codec-mjVr_wwJ.js"])))=>i.map(i=>d[i]);
|
||||
import{d as P,j as t,a as l,e as K}from"./react-vendor-Bf9ELcll.js";import{o as W}from"./vendor-BE-_xUHH.js";import{L as z,a as I,S as J,U as Q,A as X,b as ee,c as te,M as se,C as ne,B as re,d as ae,Z as oe,e as ie,f as ce,G as R,g as le,h as de,i as ue}from"./icons-vendor-B5fJPoU1.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))c(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&c(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function c(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class he extends P.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:t.jsxs("section",{className:"max-w-md text-center",children:[t.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),t.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}let S=!1;class O extends Error{constructor(n,s){super(pe(s,n)),this.name="ApiError",this.status=n,this.code=N(s)?s.code:`http_${n}`,this.requestId=N(s)?s.request_id:void 0,this.request_id=this.requestId,this.details=N(s)?s.details:void 0,this.payload=s}}const me=()=>{S||typeof window>"u"||(S=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{S=!1}))},fe=(e,n)=>{const s=new AbortController,c=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?c():e==null||e.addEventListener("abort",c,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),e==null||e.removeEventListener("abort",c)}}},N=e=>{if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.code=="string"&&typeof n.message=="string"},pe=(e,n)=>typeof e=="string"?e:N(e)?e.message:`请求失败: ${n}`,xe=3e4,ge=(e,n)=>fetch(e,{...n,credentials:"include"}),be=typeof location>"u"?"http://localhost":location.origin,v=W({baseUrl:be,fetch:ge});function nt(e){return e}async function w(e,n={}){var c;const s=fe(n.signal,n.timeoutMs??xe);try{const r=await e(s.signal);if(r.response.status===401&&!n.skipAuthLogout&&me(),r.error!==void 0)throw new O(r.response.status,r.error);if(r.data===void 0)throw new O(r.response.status,void 0);return r.data}catch(r){throw s.signal.aborted?new Error((c=n.signal)!=null&&c.aborted?"请求已取消":"请求超时,请稍后重试"):r}finally{s.cleanup()}}const ve=async e=>{const n=await w(s=>v.POST("/api/v1/session/login",{body:e,signal:s}),{skipAuthLogout:!0});return{...n,token:n.token??void 0}},we=async e=>{const n=await w(s=>v.POST("/api/v1/session/initialize",{body:{password:e},signal:s}),{skipAuthLogout:!0});return{...n,token:n.token??void 0}},ye=async e=>w(n=>v.GET("/api/v1/session",{signal:n}),e),Le=async()=>({success:!0,message:(await w(n=>v.POST("/api/v1/session/logout",{body:{},signal:n}))).message}),U=l.createContext(void 0),je=({children:e})=>{const[n,s]=l.useState(!1),[c,r]=l.useState(!1),[i,a]=l.useState(!0),[o,u]=l.useState(!1),d=()=>{s(!1),r(!1)};l.useEffect(()=>{const x=new AbortController;let p=!0;ye({signal:x.signal}).then(b=>{if(p){if((b==null?void 0:b.initialized)===!1){u(!0),d();return}u(!1),b!=null&&b.authenticated?(s(!0),r(b.is_admin===!0)):d()}}).catch(b=>{!p||b instanceof DOMException&&b.name==="AbortError"||(u(!1),d())}).finally(()=>{p&&a(!1)});const h=()=>d();return window.addEventListener("auth:logout",h),(()=>{p=!1,x.abort(),window.removeEventListener("auth:logout",h)})},[]);const m=async x=>{const p=await ve(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},g=async x=>{const p=await we(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},f=async()=>{try{await Le()}finally{d()}};return t.jsx(U.Provider,{value:{checkingAuth:i,isLoggedIn:n,isAdmin:c,needsInit:o,signIn:m,initialize:g,signOut:f},children:e})},B=()=>{const e=l.useContext(U);if(!e)throw new Error("useSession 必须在 SessionProvider 内使用");return e},q="ydisks.sidebar.v1",Ce=()=>{try{return window.localStorage.getItem(q)==="collapsed"}catch{return!1}},_e=e=>{try{window.localStorage.setItem(q,e?"collapsed":"expanded")}catch{}},Ne=({className:e="w-full h-full text-white"})=>t.jsx("svg",{className:e,viewBox:"0 0 256 256","aria-hidden":"true",children:t.jsx("g",{stroke:"nLine truncated
|
||||
@@ -6,7 +6,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
|
||||
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
|
||||
<script type="module" crossorigin src="/static/assets/index-BcKVxEYs.js"></script>
|
||||
<script type="module" crossorigin src="/static/assets/index-C6RECy_0.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-Bf9ELcll.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/vendor-BE-_xUHH.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-B5fJPoU1.js">
|
||||
|
||||
Reference in new issue
Block a user