修正商品发货地定位逻辑

改用高德地图附近 POI 查询发货地,移除闲鱼定位接口调用。发货地改为可选项,虚拟商品可直接发布;修正闲鱼网页版要求的纬度、经度 GPS 顺序,并补充前端映射与发布测试。
This commit is contained in:
Christ committed 2026-08-13 11:44:35 +08:00
1 parent 65bcb8f15c
commit ac85ac8a0a
15 files changed
+255 -214

No files matched your search

+2
View File
@@ -317,6 +317,8 @@ DATABASE_URL > -db-url > -db
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | 源码 `false` / Docker `true` | 跳过下载 |
| `TZ` | 系统时区;Docker 为 `Asia/Shanghai` | 容器和日志时区 |
前端构建还支持 `VITE_AMAP_JS_KEY`,用于覆盖发布页高德 JS API 的公开 Key;未设置时使用内置的公开 Key。修改后需重新执行 `make frontend` 才会写入嵌入式前端资源。
Docker Compose 还支持:
| 变量 | 默认值 | 说明 |
+9 -11
View File
@@ -9,7 +9,6 @@ import {
createItem,
publishItem,
recommendPublishCategory,
getPublishLocations,
previewItemPublishBatch,
startItemPublishBatch,
getItemPublishBatch,
@@ -22,6 +21,7 @@ import {
getShippingRules
} from '../services/api';
import type { PublishLocation } from '../services/api';
import { getPublishLocations } from '../services/amapLocation';
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, LocateFixed, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
interface ItemListProps {
@@ -292,13 +292,12 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
if (!publishForm.title.trim()) return alert('请填写商品标题');
if (!publishForm.price.trim()) return alert('请填写商品价格');
if (!publishForm.quantity || Number(publishForm.quantity) <= 0) return alert('库存数量必须大于 0');
if (publishForm.images.length === 0) return alert('至少上传 1 张商品图片');
if (publishForm.postage_mode === 'fixed' && !publishForm.postage.trim()) return alert('请填写一口价邮费');
if (!publishLocation) return alert('请获取当前位置并选择发货地');
if (publishForm.images.length === 0) return alert('至少上传 1 张商品图片');
if (publishForm.postage_mode === 'fixed' && !publishForm.postage.trim()) return alert('请填写一口价邮费');
setPublishing(true);
try {
const result = await publishItem({ ...publishForm, location: publishLocation });
const result = await publishItem({ ...publishForm, location: publishLocation || undefined });
await loadItems();
setShowPublishModal(false);
setPublishForm({
@@ -409,7 +408,6 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
const handlePreviewBatch = async () => {
if (!batchFile) return alert('请先上传商品表格');
if (!selectedAccount) return alert('请先选择默认发布账号');
if (!batchLocation) return alert('请获取当前位置并选择发货地');
setBatchLoading(true);
try {
const result = await previewItemPublishBatch({
@@ -417,7 +415,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
imagesZip: batchImagesZip,
defaultCookieId: selectedAccount,
fallbackCategory: batchFallbackCategory,
location: batchLocation!,
location: batchLocation || undefined,
});
setBatchPreview(result);
setBatchDetail(null);
@@ -538,8 +536,8 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
setLocationLoading(true);
navigator.geolocation.getCurrentPosition(async position => {
try {
const locations = await getPublishLocations(cookieId, position.coords.longitude, position.coords.latitude);
if (!locations.length) throw new Error('当前位置没有可用的发货地');
const locations = await getPublishLocations(position.coords.longitude, position.coords.latitude);
if (!locations.length) throw new Error('当前位置附近没有可用的高德发货地,请稍后重试');
if (batch) { setBatchLocations(locations); setBatchLocation(locations[0]); }
else { setPublishLocations(locations); setPublishLocation(locations[0]); }
} catch (error: any) {
@@ -906,7 +904,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
)}
<div className="rounded-2xl border border-sky-200 bg-sky-50 p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<div><div className="text-sm font-extrabold text-gray-900">发货地</div><p className="mt-1 text-xs text-sky-800">使用当前位置向闲鱼查询可发布的行政区。</p></div>
<div><div className="text-sm font-extrabold text-gray-900">发货地(可选)</div><p className="mt-1 text-xs text-sky-800">虚拟商品无需发货地;发布失败时可再定位并作为补充信息提交。</p></div>
<button type="button" disabled={locationLoading || !publishForm.cookie_id} onClick={() => void locateForPublish(false)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
<LocateFixed className="h-4 w-4" />{locationLoading ? '定位中...' : '获取当前位置'}
</button>
@@ -1067,7 +1065,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<div className="rounded-xl border border-sky-200 bg-sky-50 p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<div><div className="text-sm font-extrabold text-gray-900">批次发货地</div><p className="mt-1 text-xs text-sky-800">整个批次使用同一个发货地,并随任务保存用于恢复和重试。</p></div>
<div><div className="text-sm font-extrabold text-gray-900">批次发货地(可选)</div><p className="mt-1 text-xs text-sky-800">虚拟商品可留空;填写后整个批次使用同一个发货地,并随任务保存用于恢复和重试。</p></div>
<button type="button" disabled={locationLoading || !selectedAccount} onClick={() => void locateForPublish(true)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
<LocateFixed className="h-4 w-4" />{locationLoading ? '定位中...' : '获取当前位置'}
</button>
+35
View File
@@ -0,0 +1,35 @@
import { expect, test } from 'vitest';
import { amapPOIToPublishLocation } from './amapLocation';
test('maps AMap POI fields to the publish location shape', () => {
expect(amapPOIToPublishLocation({
id: 'B000A74398',
name: '人民广场',
address: '人民大道',
adname: '黄浦区',
cityname: '上海市',
adcode: '310101',
pname: '上海市',
location: { lng: 121.4737, lat: 31.2304 },
})).toEqual({
area: '黄浦区',
city: '上海市',
division_id: '310101',
longitude: 121.4737,
latitude: 31.2304,
poi_id: 'B000A74398',
poi_name: '人民广场',
province: '上海市',
});
});
test('drops incomplete or invalid AMap POIs', () => {
expect(amapPOIToPublishLocation({
id: 'poi',
name: '无坐标',
adcode: '310101',
pname: '上海市',
cityname: '上海市',
location: { lng: 0, lat: 31.2 },
})).toBeNull();
});
+153
View File
@@ -0,0 +1,153 @@
import type { PublishLocation } from './api';
const AMAP_SCRIPT_ID = 'ydisks-amap-js-api';
// 高德 JS API 的 Key 是前端公开 Key;部署时可通过 VITE_AMAP_JS_KEY 覆盖。
const DEFAULT_AMAP_JS_KEY = 'c9b68d4ce9a2a97f22a4a439404488ca';
export interface AMapLocationValue {
lng: number;
lat: number;
}
export interface AMapPOI {
id?: string;
name?: string;
address?: string;
adname?: string;
cityname?: string;
adcode?: string | number;
pname?: string;
location?: AMapLocationValue;
}
interface AMapPlaceSearchResult {
poiList?: {
pois?: AMapPOI[];
};
}
interface AMapPlaceSearch {
searchNearBy(
keyword: string,
center: [number, number],
radius: number,
callback: (status: string, result: AMapPlaceSearchResult) => void,
): void;
}
interface AMapAPI {
PlaceSearch: new (options: { extensions: 'all'; pageSize: number }) => AMapPlaceSearch;
}
declare global {
interface Window {
AMap?: AMapAPI;
__ydisksAmapLoaded?: () => void;
}
interface ImportMetaEnv {
readonly VITE_AMAP_JS_KEY?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
}
let amapLoadPromise: Promise<AMapAPI> | null = null;
const configuredAmapKey = (): string => {
const key = import.meta.env.VITE_AMAP_JS_KEY?.trim();
return key || DEFAULT_AMAP_JS_KEY;
};
const loadAMap = (): Promise<AMapAPI> => {
if (window.AMap) return Promise.resolve(window.AMap);
if (amapLoadPromise) return amapLoadPromise;
amapLoadPromise = new Promise<AMapAPI>((resolve, reject) => {
const existing = document.getElementById(AMAP_SCRIPT_ID) as HTMLScriptElement | null;
const script = existing || document.createElement('script');
const cleanup = () => {
window.__ydisksAmapLoaded = undefined;
window.clearTimeout(timeout);
};
const finish = () => {
if (window.AMap) {
cleanup();
resolve(window.AMap);
} else {
cleanup();
reject(new Error('高德地图 API 加载完成但未找到 AMap 对象'));
}
};
const timeout = window.setTimeout(() => {
cleanup();
reject(new Error('高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置'));
}, 15_000);
window.__ydisksAmapLoaded = finish;
script.id = AMAP_SCRIPT_ID;
script.async = true;
script.src = `https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(configuredAmapKey())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`;
script.onerror = () => {
cleanup();
reject(new Error('高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置'));
};
if (!existing) document.head.appendChild(script);
}).catch(error => {
amapLoadPromise = null;
throw error;
});
return amapLoadPromise;
};
const validCoordinate = (value: number): boolean => Number.isFinite(value) && value !== 0;
// 字段映射与闲鱼网页版发布页一致:adcode → divisionId,name → poi,pname/cityname/adname → 行政区。
export const amapPOIToPublishLocation = (poi: AMapPOI): PublishLocation | null => {
const longitude = Number(poi.location?.lng);
const latitude = Number(poi.location?.lat);
const location: PublishLocation = {
area: String(poi.adname || '').trim(),
city: String(poi.cityname || '').trim(),
division_id: String(poi.adcode || '').trim(),
longitude,
latitude,
poi_id: String(poi.id || '').trim(),
poi_name: String(poi.name || '').trim(),
province: String(poi.pname || '').trim(),
};
if (!location.division_id || !location.province || !location.city || !location.poi_id || !location.poi_name) {
return null;
}
if (!validCoordinate(longitude) || !validCoordinate(latitude) || longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) {
return null;
}
return location;
};
export const getPublishLocations = async (longitude: number, latitude: number): Promise<PublishLocation[]> => {
if (!validCoordinate(longitude) || !validCoordinate(latitude) || longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) {
throw new Error('经纬度无效');
}
const amap = await loadAMap();
return new Promise<PublishLocation[]>((resolve, reject) => {
const placeSearch = new amap.PlaceSearch({ extensions: 'all', pageSize: 10 });
placeSearch.searchNearBy('', [longitude, latitude], 1_000, (status, result) => {
if (status !== 'complete') {
if (status === 'no_data') {
resolve([]);
return;
}
reject(new Error('高德地图附近地址查询失败,请稍后重试'));
return;
}
const locations = (result?.poiList?.pois || [])
.map(amapPOIToPublishLocation)
.filter((location): location is PublishLocation => location !== null);
resolve(locations);
});
});
};
+19 -2
View File
@@ -17,8 +17,9 @@ import {
getShippingRules,
getShippingRulesPage,
getSystemSettings,
getValidOrders,
logout,
getValidOrders,
publishItem,
logout,
importOrders,
passwordLogin,
resolveAutomationRun,
@@ -228,6 +229,22 @@ test('deleteItemPublishBatch removes an abandoned preview', async () => {
}));
});
test('publishItem allows virtual publishing without an optional location', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
await publishItem({
cookie_id: 'acc1',
title: '虚拟商品',
description: '',
price: '12.50',
quantity: 1,
postage_mode: 'none',
images: [],
});
const body = fetchMock.mock.calls[0][1].body as FormData;
expect(body.get('location')).toBeNull();
});
test('getItems normalizes multi-spec flags from backend values', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
cookie_id: 'cookie-1',
+4 -9
View File
@@ -526,7 +526,7 @@ export const publishItem = async (form: {
postage_mode: string;
postage?: string;
images: File[];
location: PublishLocation;
location?: PublishLocation;
}): Promise<any> => {
const body = new FormData();
body.set('cookie_id', form.cookie_id);
@@ -537,7 +537,7 @@ export const publishItem = async (form: {
body.set('quantity', String(form.quantity));
body.set('postage_mode', form.postage_mode);
body.set('postage', form.postage || '');
body.set('location', JSON.stringify(form.location));
if (form.location) body.set('location', JSON.stringify(form.location));
for (const file of form.images) {
body.append('images', file);
}
@@ -555,11 +555,6 @@ export interface PublishLocation {
province: string;
}
export const getPublishLocations = async (cookieId: string, longitude: number, latitude: number): Promise<PublishLocation[]> => {
const result = await post<any>('/items/publish-locations', { cookie_id: cookieId, longitude, latitude });
return Array.isArray(result?.locations) ? result.locations : [];
}
export const recommendPublishCategory = async (cookieId: string, keyword: string): Promise<{
success: boolean;
category: {
@@ -582,7 +577,7 @@ export const previewItemPublishBatch = async (form: {
channelCatId?: string;
tbCatId?: string;
};
location: PublishLocation;
location?: PublishLocation;
}): Promise<any> => {
const body = new FormData();
body.set('file', form.file);
@@ -592,7 +587,7 @@ export const previewItemPublishBatch = async (form: {
body.set('fallback_category_name', form.fallbackCategory.catName);
body.set('fallback_channel_category_id', form.fallbackCategory.channelCatId || '');
body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || '');
body.set('location', JSON.stringify(form.location));
if (form.location) body.set('location', JSON.stringify(form.location));
return postForm('/items/publish-batches/preview', body);
}
-52
View File
@@ -23,7 +23,6 @@ func (s *Server) mountItemsReal(r chi.Router) {
r.Post("/items/get-all-from-account", s.syncItemsFromAccount)
r.Post("/items/get-by-page", s.syncItemsPageFromAccount)
r.Post("/items/publish", s.publishItem)
r.Post("/items/publish-locations", s.publishLocations)
r.Post("/items/publish-categories/recommend", s.recommendItemPublishCategory)
r.Post("/items/publish-batches/preview", s.previewItemPublishBatch)
r.Post("/items/publish-batches", s.startItemPublishBatch)
@@ -42,57 +41,6 @@ func (s *Server) mountItemsReal(r chi.Router) {
r.Put("/items/{cookie_id}/{item_id}/multi-quantity-delivery", s.setItemMultiQuantity)
}
func (s *Server) publishLocations(w http.ResponseWriter, r *http.Request) {
var req struct {
CookieID string `json:"cookie_id"`
Longitude float64 `json:"longitude"`
Latitude float64 `json:"latitude"`
}
if err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.CookieID) == "" {
writeErr(w, http.StatusBadRequest, "请选择账号并提供当前位置")
return
}
_, userID, ok := s.cookieForCurrentUser(w, r, strings.TrimSpace(req.CookieID))
if !ok {
return
}
credentialUnlock := s.Store.LockAccountCredentials(req.CookieID)
defer credentialUnlock()
latest, err := s.Store.Cookies.GetDetails(r.Context(), req.CookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
locator, ok := s.mtopClient().(interface {
PublishLocations(context.Context, string, float64, float64) ([]mtop.PublishLocation, string, error)
})
if !ok {
writeErr(w, http.StatusNotImplemented, "当前客户端不支持查询发货地")
return
}
locations, updated, callErr := locator.PublishLocations(mtopCtx, latest.Value, req.Longitude, req.Latitude)
value, changed, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if persistErr != nil {
writeErr(w, http.StatusInternalServerError, "保存账号登录状态失败")
return
}
if !handled && updated != "" && updated != latest.Value {
if err := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, updated, userID); err == nil {
s.updateRunningCookie(r.Context(), req.CookieID, updated)
}
} else if handled && changed {
s.updateRunningCookie(r.Context(), req.CookieID, value)
}
if callErr != nil {
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "locations": locations})
}
func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
// 最多 9 张 10 MiB 图片,额外预留 multipart 元数据空间。
r.Body = http.MaxBytesReader(w, r.Body, maxItemPublishBytes)
-4
View File
@@ -241,8 +241,6 @@ func TestPublishItemSuccess(t *testing.T) {
switch {
case strings.Contains(u, "stream-upload.goofish.com"):
respBody = `{"object":{"url":"https://img.alicdn.com/published.png","pix":"800_800"}}`
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"99","catName":"数码"}}}`
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
@@ -330,8 +328,6 @@ func TestPublishItemStockPermissionMissing(t *testing.T) {
switch {
case strings.Contains(u, "stream-upload.goofish.com"):
respBody = `{"object":{"url":"https://img.alicdn.com/published.png","pix":"800_800"}}`
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
respBody = `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"99","catName":"数码"}}}`
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
@@ -311,8 +311,6 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
switch {
case strings.Contains(u, "stream-upload.goofish.com"):
body = `{"object":{"url":"https://img.alicdn.com/published.png","pix":"800_800"}}`
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
body = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
body = `{"ret":["SUCCESS::调用成功"],"data":{}}`
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
@@ -1,19 +0,0 @@
import{j as e,r,b as Me,c as oa,d as Ta}from"./react-vendor-C_od1ZSF.js";import{L as Ma,U as ca,M as as,C as ls,B as da,S as xa,Z as rs,a as jt,b as hs,c as gs,d as bs,e as qa,f as at,A as Cs,D as Fa,g as Ss,P as ma,h as Et,E as pa,T as Ba,i as za,j as De,X as Te,k as Ua,l as Wa,m as fs,n as ua,o as Ge,Q as Kt,p as xt,q as Qe,r as yt,s as Pt,t as Ls,R as Be,u as ha,v as Ja,w as Je,K as Va,x as dt,y as st,z as Ye,F as Os,G as _t,H as Nt,I as $t,J as ga,N as Qa,O as Is,V as As,W as Ga,Y as Ka,_ as Ha,$ as Za,a0 as Ht,a1 as Mt,a2 as ns,a3 as Ya,a4 as Xa,a5 as is,a6 as Rs,a7 as el,a8 as tl,a9 as Dt,aa as $s,ab as Jt,ac as ba,ad as sl,ae as al,af as Qt,ag as fa,ah as ll,ai as rl,aj as nl,ak as il,al as ol,am as cl,an as Ps}from"./icons-vendor-DF3hof7q.js";import{R as qt,B as dl,X as Ds,Y as Es,T as Ft,a as xl,C as Zt,A as ml,b as pl,c as ul,P as Ts,d as Ms,L as hl}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const p of document.querySelectorAll('link[rel="modulepreload"]'))o(p);new MutationObserver(p=>{for(const k of p)if(k.type==="childList")for(const C of k.addedNodes)C.tagName==="LINK"&&C.rel==="modulepreload"&&o(C)}).observe(document,{childList:!0,subtree:!0});function l(p){const k={};return p.integrity&&(k.integrity=p.integrity),p.referrerPolicy&&(k.referrerPolicy=p.referrerPolicy),p.crossOrigin==="use-credentials"?k.credentials="include":p.crossOrigin==="anonymous"?k.credentials="omit":k.credentials="same-origin",k}function o(p){if(p.ep)return;p.ep=!0;const k=l(p);fetch(p.href,k)}})();const gl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),os=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25Line 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(hs,{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:Ve,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:F,children:"取消"}),e.jsxs("button",{onClick:Lt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:F,children:[F?e.jsx(De,{className:"w-4 h-4 animate-spin"}):e.jsx(Ge,{className:"w-4 h-4"}),F?"保存中...":"保存"]})]})})]})}),document.body)]})},Xr=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(s=>({order_id:String((s==null?void 0:s.order_id)||"unknown"),success:(s==null?void 0:s.success)===!0,message:String((s==null?void 0:s.message)||"")})):[]}),en=t=>(t==null?void 0:t.results.filter(s=>!s.success))||[],Hs=({status:t})=>{const s={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${s[t]||s.cancelled}`,children:l[t]||t})},tn=()=>{const[t,s]=r.useState([]),[l,o]=r.useState([]),[p,k]=r.useState([]),[C,A]=r.useState({}),[f,O]=r.useState("all"),[j,V]=r.useState(""),[Y,pe]=r.useState(""),[ce,v]=r.useState(""),q=r.useRef(0),[de,G]=r.useState(1),[X,U]=r.useState(1),[fe,ge]=r.useState(!1),[L,K]=r.useState(!1),[ae,Z]=r.useState(!1),[me,R]=r.useState(!1),[D,ee]=r.useState(null),[T,se]=r.useState(null),[Ce,ye]=r.useState({}),[z,x]=r.useState(!1),[b,W]=r.useState(""),[M,ne]=r.useState(!1),[be,ve]=r.useState(null),[Ee,_e]=r.useState(null),[c,S]=r.useState(null),[Q,u]=r.useState(!1),[d,F]=r.useState(null),[I,H]=r.useState(null),$=async()=>{const m=++q.current;ge(!0);try{const P=await Ql(j||void 0,f,de,20,ce);if(m!==q.current)return;s(P.data),U(P.total_pages)}catch(P){console.error("加载订单失败:",P)}finally{m===q.current&&ge(!1)}},Se=(m,P,ie)=>{if(ie&&ie.trim())return ie;if(C[`${m}:${P}`])return C[`${m}:${P}`];const re=l.find(ze=>{if(ie&&ze.item_title){const He=ie.toLowerCase(),Xe=ze.item_title.toLowerCase();return Xe.includes(He)||He.includes(Xe)}return!1});return re!=null&&re.item_title?re.item_title:"未知商品"},Re=m=>{const P={};m.forEach(ie=>{ie.item_id&&(P[`${ie.cookie_id}:${ie.item_id}`]=ie.item_title||ie.item_id)}),A(P)};r.useEffect(()=>{const m=window.setTimeout(()=>{G(1),v(Y.trim())},300);return()=>window.clearTimeout(m)},[Y]),r.useEffect(()=>{$()},[j,f,de,ce]),r.useEffect(()=>{Promise.all([Tt(),vt()]).then(([m,P])=>{k(m),o(P),Re(P)}).catch(m=>{console.error("加载商品列表失败:",m)})},[]);const xe=r.useMemo(()=>new Map(p.map(m=>[m.id,m])),[p]),$e=m=>{const P=xe.get(m),ie=(P==null?void 0:P.remark)||(P==null?void 0:P.nickname);return ie?`${ie} · ${m.slice(0,6)}`:`账号 ${m.slice(0,8)}`},le=m=>{const P=xe.get(m);return(P==null?void 0:P.remark)||(P==null?void 0:P.nickname)||"未命名账号"},g=async()=>{ge(!0);try{const m=await Hl(j||void 0,f);await $(),m!=null&&m.message&&alert(m.message)}catch(m){console.error("同步订单失败:",m),alert((m==null?void 0:m.message)||"同步失败,请重试")}finally{ge(!1)}},y=m=>{W(m),ve(null),x(!0)},E=async m=>{var P;ne(!0),ve(null);try{const ie=await Yl([b],m),re=(P=ie==null?void 0:ie.results)==null?void 0:P[0];re!=null&&re.success?(ve({success:!0,message:re.message}),$()):ve({success:!1,message:(re==null?void 0:re.message)||"发货失败"})}catch(ie){ve({success:!1,message:(ie==null?void 0:ie.message)||"请求失败"})}finally{ne(!1)}},J=m=>{ee(m),K(!0)},Le=m=>{se({...m}),Z(!0)},Pe=async()=>{if(!(!T||!T.order_id))try{const m={};T.status!==void 0&&(m.order_status=T.status),T.buyer_id!==void 0&&(m.buyer_id=T.buyer_id),T.amount!==void 0&&(m.amount=T.amount),T.receiver_name!==void 0&&(m.receiver_name=T.receiver_name),T.receiver_phone! Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(I=>I.map(H=>`"${String(H).replace(/"/g,'""')}"`).join(",")).join(`
`),u=new Blob(["\uFEFF"+Q],{type:"text/csv;charset=utf-8"}),d=URL.createObjectURL(u),F=document.createElement("a");F.href=d,F.download="卡密组批量导入模板.csv",document.body.appendChild(F),F.click(),F.remove(),URL.revokeObjectURL(d)},ve=async()=>{if(q){fe(!0),X(null);try{const c=await rr(q);if(X(c),c.created>0){const S=await Ze();s(S)}}catch(c){X({error:(c==null?void 0:c.message)||"上传失败"})}finally{fe(!1)}}},Ee=async()=>{if(!(!ge||!K.trim())){fe(!0),me(null);try{const c=await nr(ge,K);me({added:c.added}),ae("");const S=await Ze();s(S)}catch(c){alert("追加失败:"+((c==null?void 0:c.message)||"未知错误"))}finally{fe(!1)}}},_e=()=>{var c;v("create"),de(null),X(null),L((c=M[0])!=null&&c.id?String(M[0].id):""),ae(""),me(null),pe(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:_e,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx($t,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>k(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Ye,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ga,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:R,onChange:c=>D(c.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(_t,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:ee,onChange:c=>T(c.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",ne.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:ne.map(c=>{let S="";return c.type==="data"&&c.data_content?S=`库存: ${c.data_content.split(`
`).filter(u=>u.trim()).length} 条`:c.type==="text"&&c.text_content?S=c.text_content:c.type==="api"&&c.api_config?S=c.api_config.url:c.type==="image"&&c.image_url&&(S="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(se,{type:c.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:c.name,children:c.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>W(c.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:c.id}),e.jsx(Qa,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${c.type==="text"?"bg-blue-50 text-blue-600":c.type==="data"?"bg-purple-50 text-purple-600":c.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:c.type==="text"?"文本":c.type==="data"?"批量":c.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:S,children:S})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:c.description||"-",children:c.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>b(c),className:`w-12 h-8 rounded-full relative transition-colors ${c.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${c.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>Ce(c),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(Nt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>z(c.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Je,{className:"h-4 w-4"})})]})})]},c.id)})})]})}),ne.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ma,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&C&&Me.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>o(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Te,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:f.name||"",onChange:c=>O({...f,name:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:f.type||"text",onChange:c=>O({...f,type:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(C==null?void 0:C.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),f.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:f.api_url||"",onChange:c=>O({...f,api_url:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:f.data_content?f.data_content.split(`
`).filter(c=>c.trim()).length:0})," 条"]})]})]}),f.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:f.image_url||"",onChange:c=>O({...f,image_url:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),f.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:f.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:c=>{c.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:f.delay_seconds||0,onChange:c=>O({...f,delay_seconds:parseInt(c.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:f.description||"",onChange:c=>O({...f,description:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>O({...f,enabled:!f.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${f.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${f.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>o(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ye,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),p&&Me.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>k(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Te,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:j.name,onChange:c=>V({...j,name:c.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>V({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(ls,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>V({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Is,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>V({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),j.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:j.content.split(`
`).filter(c=>c.trim()).length})," 条"]})]}),j.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:j.api_method,onChange:c=>V({...j,api_method:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:j.api_timeout,onChange:c=>V({...j,api_timeout:parseInt(c.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:j.api_headers,onChange:c=>V({...j,api_headers:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:j.api_params,onChange:c=>V({...j,api_params:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:j.description,onChange:c=>V({...j,description:c.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:j.delay_seconds,onChange:c=>V({...j,delay_seconds:parseInt(c.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>k(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:x,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ye,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),Y&&Me.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>pe(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Te,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>v("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ce==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ga,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>v("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ce==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx($t,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),ce==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:be,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm tran Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),Z&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",Z.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>pe(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),ce==="create"?e.jsxs("button",{onClick:ve,disabled:!q||U,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[U?e.jsx(De,{className:"w-4 h-4 animate-spin"}):e.jsx($t,{className:"w-4 h-4"}),U?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Ee,disabled:!ge||!K.trim()||U||M.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[U?e.jsx(De,{className:"w-4 h-4 animate-spin"}):e.jsx(Ye,{className:"w-4 h-4"}),U?"处理中...":"追加卡密"]})]})]})}),document.body)]})},ln=t=>t.find(s=>s.status==="running"||s.status==="canceling"),rn=t=>{const s=String(t||"").trim();return s?/^[¥¥]/.test(s)?s:`¥${s}`:"-"},nn=({onConfigureDelivery:t})=>{const[s,l]=r.useState([]),[o,p]=r.useState([]),[k,C]=r.useState([]),[A,f]=r.useState(""),[O,j]=r.useState(""),[V,Y]=r.useState(!1),[pe,ce]=r.useState(!1),[v,q]=r.useState(!1),[de,G]=r.useState(!1),[X,U]=r.useState(!1),[fe,ge]=r.useState(!1),[L,K]=r.useState(!1),[ae,Z]=r.useState("upload"),[me,R]=r.useState(null),[D,ee]=r.useState(null),[T,se]=r.useState(""),[Ce,ye]=r.useState(!1),[z,x]=r.useState(!1),[b,W]=r.useState([]),[M,ne]=r.useState(null),[be,ve]=r.useState([]),[Ee,_e]=r.useState(null),[c,S]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[Q,u]=r.useState(null),[d,F]=r.useState(null),[I,H]=r.useState(null),$=r.useRef(!1),[Se,Re]=r.useState(null),[xe,$e]=r.useState({}),[le,g]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[y,E]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[J,Le]=r.useState([]);r.useEffect(()=>{if(!fe||y.images.length===0){Le([]);return}const n=y.images.map((w,i)=>({key:w.name+i,url:URL.createObjectURL(w)}));return Le(n),()=>{n.forEach(w=>URL.revokeObjectURL(w.url))}},[fe,y.images]);const Pe=async()=>{const n=await vt();l(n)},Oe=async()=>{p(await ms())};r.useEffect(()=>{Promise.all([Tt(),vt(),ms(),Ws(20)]).then(([n,w,i,_])=>{C(n),l(w),p(i);const a=_.find(h=>["running","canceling"].includes(h.status))||_.find(h=>h.status!=="preview");H(a||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!L||!(d!=null&&d.id)||!["running","canceling"].includes(d.status))return;const n=window.setInterval(async()=>{if(!$.current){$.current=!0;try{const w=await bt(d.id);F(w),H(w),["running","canceling"].includes(w.status)||(Z("done"),await Pe(),await Oe())}catch(w){console.error("刷新批量铺货进度失败:",w)}finally{$.current=!1}}},3e3);return()=>{window.clearInterval(n)}},[L,d==null?void 0:d.id,d==null?void 0:d.status]);const Ae=async()=>{if(!A)return alert("请先选择账号");Y(!0);try{const n=await ir(A);await Pe(),alert((n==null?void 0:n.message)||"商品同步完成")}catch(n){console.error("同步商品失败:",n),alert((n==null?void 0:n.message)||"同步失败,请重试")}finally{Y(!1)}},te=n=>{Re(n),$e({...n}),G(!0)},je=async()=>{if(Se)try{await fr(Se.cookie_id,Se.item_id,{item_title:xe.item_title||"",item_description:xe.item_description||"",item_category:xe.item_category||"",item_price:xe.item_price||"",item_detail:xe.item_detail||Se.item_detail||""}),await Pe(),await Oe(),G(!1),Re(null)}catch(n){console.error("更新商品失败:",n),alert("更新失败,请重试")}},m=async n=>{if(confirm(`确认删除商品"${n.item_title}"吗?`))try{await or(n.cookie_id,n.item_id),l(w=>w.filter(i=>!(i.cookie_id===n.cookie_id&&i.item_id===n.item_id)))}catch(w){console.error("删除商品失败:",w),alert("删除失败,请重试")}},P=async()=>{try{if(!le.cookie_id||!le.item_id){alert("请选择账号并填写商品ID");return}await cr(le.cookie_id,{item_id:le.item_id,item_title:le.item_title,item_price:le.item_price,item_detail:le.item_image?JSON.stringify({item_image:le.item_image}):""}),await Pe(),U(!1),g({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(n){console.error("添加商品失败:",n),alert("添加失败,请重试")}},ie=async()=>{if(!y.cookie_id)return alert("请选择发布账号");if(!y.title.trim())return alert("请填写商品标题");if(!y.price.trim())return alert("请填写商品价格");if(!y.quantity||Number(y.quantity)<=0)return alert("库存数 Line truncated
`),_=new Blob(["\uFEFF"+i],{type:"text/csv;charset=utf-8"}),a=URL.createObjectURL(_),h=document.createElement("a");h.href=a,h.download="批量铺货模板.csv",document.body.appendChild(h),h.click(),h.remove(),URL.revokeObjectURL(a)},St=()=>{g(n=>({...n,cookie_id:A||n.cookie_id})),U(!0)},lt=()=>{E(n=>({...n,cookie_id:A||n.cookie_id})),ge(!0)},rt=async n=>{const w=n?A:y.cookie_id;if(!w)return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");x(!0),navigator.geolocation.getCurrentPosition(async i=>{try{const _=await xr(w,i.coords.longitude,i.coords.latitude);if(!_.length)throw new Error("当前位置没有可用的发货地");n?(ve(_),_e(_[0])):(W(_),ne(_[0]))}catch(_){alert((_==null?void 0:_.message)||"获取发货地失败")}finally{x(!1)}},i=>{x(!1),alert(i.code===i.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Lt=n=>o.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id).length>0?o.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id):o.filter(w=>w.cookie_id===n.cookie_id&&!w.item_id),nt=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},ut=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},et=r.useMemo(()=>new Map(k.map(n=>[n.id,n])),[k]),it=r.useMemo(()=>O?s.filter(n=>n.cookie_id===O):s,[O,s]),Ve=n=>{const w=et.get(n),i=(w==null?void 0:w.remark)||(w==null?void 0:w.nickname);return i?`${i} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},ht=n=>{const w=et.get(n);return(w==null?void 0:w.remark)||(w==null?void 0:w.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Za,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:O,onChange:n=>j(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),k.map(n=>e.jsx("option",{value:n.id,children:Ve(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:A,onChange:n=>f(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),k.map(n=>e.jsx("option",{value:n.id,children:Ve(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:Ae,disabled:V||!A,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Be,{className:`w-4 h-4 ${V?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:St,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(Ye,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:lt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Ht,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void re(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transi Line truncated
@@ -0,0 +1,19 @@
import{j as e,r,b as Me,c as xa,d as Fa}from"./react-vendor-C_od1ZSF.js";import{L as Ba,U as ma,M as rs,C as ns,B as pa,S as ua,Z as is,a as jt,b as bs,c as fs,d as ys,e as za,f as at,A as Ls,D as Ua,g as Os,P as ha,h as Tt,E as ga,T as Wa,i as Ja,j as Ee,X as Te,k as Va,l as Qa,m as js,n as ba,o as Ge,Q as Zt,p as xt,q as Qe,r as yt,s as Et,t as Is,R as Be,u as fa,v as Ga,w as Je,K as Ka,x as dt,y as st,z as Ye,F as As,G as Nt,H as _t,I as $t,J as ya,N as Ha,O as Rs,V as Ps,W as Za,Y as Ya,_ as Xa,$ as el,a0 as Yt,a1 as qt,a2 as os,a3 as tl,a4 as sl,a5 as cs,a6 as $s,a7 as al,a8 as ll,a9 as Dt,aa as Es,ab as Vt,ac as ja,ad as rl,ae as nl,af as Kt,ag as _a,ah as il,ai as ol,aj as cl,ak as dl,al as xl,am as ml,an as Ds}from"./icons-vendor-DF3hof7q.js";import{R as Ft,B as pl,X as Ts,Y as Ms,T as Bt,a as ul,C as Xt,A as hl,b as gl,c as bl,P as qs,d as Fs,L as fl}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const x of document.querySelectorAll('link[rel="modulepreload"]'))o(x);new MutationObserver(x=>{for(const v of x)if(v.type==="childList")for(const k of v.addedNodes)k.tagName==="LINK"&&k.rel==="modulepreload"&&o(k)}).observe(document,{childList:!0,subtree:!0});function l(x){const v={};return x.integrity&&(v.integrity=x.integrity),x.referrerPolicy&&(v.referrerPolicy=x.referrerPolicy),x.crossOrigin==="use-credentials"?v.credentials="include":x.crossOrigin==="anonymous"?v.credentials="omit":v.credentials="same-origin",v}function o(x){if(x.ep)return;x.ep=!0;const v=l(x);fetch(x.href,v)}})();const yl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ds=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25Line 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(bs,{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:Ve,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:F,children:"取消"}),e.jsxs("button",{onClick:Lt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:F,children:[F?e.jsx(Ee,{className:"w-4 h-4 animate-spin"}):e.jsx(Ge,{className:"w-4 h-4"}),F?"保存中...":"保存"]})]})})]})}),document.body)]})},tn=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(s=>({order_id:String((s==null?void 0:s.order_id)||"unknown"),success:(s==null?void 0:s.success)===!0,message:String((s==null?void 0:s.message)||"")})):[]}),sn=t=>(t==null?void 0:t.results.filter(s=>!s.success))||[],Ys=({status:t})=>{const s={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${s[t]||s.cancelled}`,children:l[t]||t})},an=()=>{const[t,s]=r.useState([]),[l,o]=r.useState([]),[x,v]=r.useState([]),[k,A]=r.useState({}),[b,O]=r.useState("all"),[j,V]=r.useState(""),[Y,pe]=r.useState(""),[ce,w]=r.useState(""),M=r.useRef(0),[de,G]=r.useState(1),[X,U]=r.useState(1),[fe,ge]=r.useState(!1),[L,K]=r.useState(!1),[ae,Z]=r.useState(!1),[me,R]=r.useState(!1),[E,ee]=r.useState(null),[T,se]=r.useState(null),[ke,ye]=r.useState({}),[z,m]=r.useState(!1),[f,W]=r.useState(""),[q,ne]=r.useState(!1),[be,ve]=r.useState(null),[De,Ne]=r.useState(null),[c,S]=r.useState(null),[Q,u]=r.useState(!1),[d,F]=r.useState(null),[I,H]=r.useState(null),P=async()=>{const p=++M.current;ge(!0);try{const $=await Hl(j||void 0,b,de,20,ce);if(p!==M.current)return;s($.data),U($.total_pages)}catch($){console.error("加载订单失败:",$)}finally{p===M.current&&ge(!1)}},Ce=(p,$,ie)=>{if(ie&&ie.trim())return ie;if(k[`${p}:${$}`])return k[`${p}:${$}`];const re=l.find(ze=>{if(ie&&ze.item_title){const He=ie.toLowerCase(),Xe=ze.item_title.toLowerCase();return Xe.includes(He)||He.includes(Xe)}return!1});return re!=null&&re.item_title?re.item_title:"未知商品"},Re=p=>{const $={};p.forEach(ie=>{ie.item_id&&($[`${ie.cookie_id}:${ie.item_id}`]=ie.item_title||ie.item_id)}),A($)};r.useEffect(()=>{const p=window.setTimeout(()=>{G(1),w(Y.trim())},300);return()=>window.clearTimeout(p)},[Y]),r.useEffect(()=>{P()},[j,b,de,ce]),r.useEffect(()=>{Promise.all([Mt(),vt()]).then(([p,$])=>{v(p),o($),Re($)}).catch(p=>{console.error("加载商品列表失败:",p)})},[]);const xe=r.useMemo(()=>new Map(x.map(p=>[p.id,p])),[x]),Pe=p=>{const $=xe.get(p),ie=($==null?void 0:$.remark)||($==null?void 0:$.nickname);return ie?`${ie} · ${p.slice(0,6)}`:`账号 ${p.slice(0,8)}`},le=p=>{const $=xe.get(p);return($==null?void 0:$.remark)||($==null?void 0:$.nickname)||"未命名账号"},g=async()=>{ge(!0);try{const p=await Xl(j||void 0,b);await P(),p!=null&&p.message&&alert(p.message)}catch(p){console.error("同步订单失败:",p),alert((p==null?void 0:p.message)||"同步失败,请重试")}finally{ge(!1)}},y=p=>{W(p),ve(null),m(!0)},D=async p=>{var $;ne(!0),ve(null);try{const ie=await tr([f],p),re=($=ie==null?void 0:ie.results)==null?void 0:$[0];re!=null&&re.success?(ve({success:!0,message:re.message}),P()):ve({success:!1,message:(re==null?void 0:re.message)||"发货失败"})}catch(ie){ve({success:!1,message:(ie==null?void 0:ie.message)||"请求失败"})}finally{ne(!1)}},J=p=>{ee(p),K(!0)},Se=p=>{se({...p}),Z(!0)},$e=async()=>{if(!(!T||!T.order_id))try{const p={};T.status!==void 0&&(p.order_status=T.status),T.buyer_id!==void 0&&(p.buyer_id=T.buyer_id),T.amount!==void 0&&(p.amount=T.amount),T.receiver_name!==void 0&&(p.receiver_name=T.receiver_name),T.receiver_phone! Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(I=>I.map(H=>`"${String(H).replace(/"/g,'""')}"`).join(",")).join(`
`),u=new Blob(["\uFEFF"+Q],{type:"text/csv;charset=utf-8"}),d=URL.createObjectURL(u),F=document.createElement("a");F.href=d,F.download="卡密组批量导入模板.csv",document.body.appendChild(F),F.click(),F.remove(),URL.revokeObjectURL(d)},ve=async()=>{if(M){fe(!0),X(null);try{const c=await or(M);if(X(c),c.created>0){const S=await Ze();s(S)}}catch(c){X({error:(c==null?void 0:c.message)||"上传失败"})}finally{fe(!1)}}},De=async()=>{if(!(!ge||!K.trim())){fe(!0),me(null);try{const c=await cr(ge,K);me({added:c.added}),ae("");const S=await Ze();s(S)}catch(c){alert("追加失败:"+((c==null?void 0:c.message)||"未知错误"))}finally{fe(!1)}}},Ne=()=>{var c;w("create"),de(null),X(null),L((c=q[0])!=null&&c.id?String(q[0].id):""),ae(""),me(null),pe(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:Ne,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx($t,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>v(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Ye,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ya,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:R,onChange:c=>E(c.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(Nt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:ee,onChange:c=>T(c.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",ne.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:ne.map(c=>{let S="";return c.type==="data"&&c.data_content?S=`库存: ${c.data_content.split(`
`).filter(u=>u.trim()).length} 条`:c.type==="text"&&c.text_content?S=c.text_content:c.type==="api"&&c.api_config?S=c.api_config.url:c.type==="image"&&c.image_url&&(S="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(se,{type:c.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:c.name,children:c.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>W(c.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:c.id}),e.jsx(Ha,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${c.type==="text"?"bg-blue-50 text-blue-600":c.type==="data"?"bg-purple-50 text-purple-600":c.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:c.type==="text"?"文本":c.type==="data"?"批量":c.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:S,children:S})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:c.description||"-",children:c.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>f(c),className:`w-12 h-8 rounded-full relative transition-colors ${c.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${c.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>ke(c),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(_t,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>z(c.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Je,{className:"h-4 w-4"})})]})})]},c.id)})})]})}),ne.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ha,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&k&&Me.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>o(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Te,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:b.name||"",onChange:c=>O({...b,name:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:b.type||"text",onChange:c=>O({...b,type:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(k==null?void 0:k.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),b.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:b.api_url||"",onChange:c=>O({...b,api_url:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:b.data_content?b.data_content.split(`
`).filter(c=>c.trim()).length:0})," 条"]})]})]}),b.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:b.image_url||"",onChange:c=>O({...b,image_url:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),b.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:b.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:c=>{c.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:b.delay_seconds||0,onChange:c=>O({...b,delay_seconds:parseInt(c.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:b.description||"",onChange:c=>O({...b,description:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>O({...b,enabled:!b.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${b.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${b.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>o(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ye,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),x&&Me.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>v(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Te,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:j.name,onChange:c=>V({...j,name:c.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>V({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(ns,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>V({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Rs,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>V({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),j.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:j.content.split(`
`).filter(c=>c.trim()).length})," 条"]})]}),j.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:j.api_method,onChange:c=>V({...j,api_method:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:j.api_timeout,onChange:c=>V({...j,api_timeout:parseInt(c.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:j.api_headers,onChange:c=>V({...j,api_headers:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:j.api_params,onChange:c=>V({...j,api_params:c.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:j.description,onChange:c=>V({...j,description:c.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:j.delay_seconds,onChange:c=>V({...j,delay_seconds:parseInt(c.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>v(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:m,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ye,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),Y&&Me.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>pe(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Te,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>w("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ce==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Za,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>w("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ce==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx($t,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),ce==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:be,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm tran Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),Z&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",Z.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>pe(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),ce==="create"?e.jsxs("button",{onClick:ve,disabled:!M||U,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[U?e.jsx(Ee,{className:"w-4 h-4 animate-spin"}):e.jsx($t,{className:"w-4 h-4"}),U?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:De,disabled:!ge||!K.trim()||U||q.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[U?e.jsx(Ee,{className:"w-4 h-4 animate-spin"}):e.jsx(Ye,{className:"w-4 h-4"}),U?"处理中...":"追加卡密"]})]})]})}),document.body)]})},nn=t=>t.find(s=>s.status==="running"||s.status==="canceling"),ea="ydisks-amap-js-api",on="c9b68d4ce9a2a97f22a4a439404488ca";let It=null;const cn=()=>on,dn=()=>window.AMap?Promise.resolve(window.AMap):It||(It=new Promise((t,s)=>{const l=document.getElementById(ea),o=l||document.createElement("script"),x=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(k)},v=()=>{window.AMap?(x(),t(window.AMap)):(x(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},k=window.setTimeout(()=>{x(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=v,o.id=ea,o.async=!0,o.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(cn())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,o.onerror=()=>{x(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},l||document.head.appendChild(o)}).catch(t=>{throw It=null,t}),It),Gt=t=>Number.isFinite(t)&&t!==0,xn=t=>{var x,v;const s=Number((x=t.location)==null?void 0:x.lng),l=Number((v=t.location)==null?void 0:v.lat),o={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:l,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!o.division_id||!o.province||!o.city||!o.poi_id||!o.poi_name||!Gt(s)||!Gt(l)||s<-180||s>180||l<-90||l>90?null:o},mn=async(t,s)=>{if(!Gt(t)||!Gt(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const l=await dn();return new Promise((o,x)=>{new l.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(k,A)=>{var O;if(k!=="complete"){if(k==="no_data"){o([]);return}x(new Error("高德地图附近地址查询失败,请稍后重试"));return}const b=(((O=A==null?void 0:A.poiList)==null?void 0:O.pois)||[]).map(xn).filter(j=>j!==null);o(b)})})},pn=t=>{const s=String(t||"").trim();return s?/^[¥¥]/.test(s)?s:`¥${s}`:"-"},un=({onConfigureDelivery:t})=>{const[s,l]=r.useState([]),[o,x]=r.useState([]),[v,k]=r.useState([]),[A,b]=r.useState(""),[O,j]=r.useState(""),[V,Y]=r.useState(!1),[pe,ce]=r.useState(!1),[w,M]=r.useState(!1),[de,G]=r.useState(!1),[X,U]=r.useState(!1),[fe,ge]=r.useState(!1),[L,K]=r.useState(!1),[ae,Z]=r.useState("upload"),[me,R]=r.useState(null),[E,ee]=r.useState(null),[T,se]=r.useState(""),[ke,ye]=r.useState(!1),[z,m]=r.useState(!1),[f,W]=r.useState([]),[q,ne]=r.useState(null),[be,ve]=r.useState([]),[De,Ne]=r.useState(null),[c,S]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[Q,u]=r.useState(null),[d,F]=r.useState(null),[I,H]=r.useState(null),P=r.useRef(!1),[Ce,Re]=r.useState(null),[xe,Pe]=r.useState({}),[le,g]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[y,D]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[J,Se]=r.useState([]);r.useEffect(()=>{if(!fe||y.images.length===0){Se([]);return}const n=y.images.map((C,i)=>({key:C.name+i,url:URL.createObjectURL(C)}));return Se(n),()=>{n.forEach(C=>URL.revokeObjectURL(C.url))}},[fe,y.images]);const $e=async()=>{const n=await vt();l(n)},Le=async()=>{x(await us())};r.useEffect(()=>{Promise.all([Mt(),vt(),us(),Vs(20)]).then(([n,C,i,N])=>{k(n),l(C),x(i);const a=N.find(h=>["running","canceling"].includes(h.status))||N.find(h=>h.status!=="preview");H(a||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!L||!(d!=null&&d.id)||!["running","canceling"].includes(d.status))return;const n=window.setInterval(async()=>{if(!P.current){P.current=!0;try{const C=await bt(d.id);F(C),H(C),["ru Line truncated
`),N=new Blob(["\uFEFF"+i],{type:"text/csv;charset=utf-8"}),a=URL.createObjectURL(N),h=document.createElement("a");h.href=a,h.download="批量铺货模板.csv",document.body.appendChild(h),h.click(),h.remove(),URL.revokeObjectURL(a)},St=()=>{g(n=>({...n,cookie_id:A||n.cookie_id})),U(!0)},lt=()=>{D(n=>({...n,cookie_id:A||n.cookie_id})),ge(!0)},rt=async n=>{if(!(n?A:y.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");m(!0),navigator.geolocation.getCurrentPosition(async i=>{try{const N=await mn(i.coords.longitude,i.coords.latitude);if(!N.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");n?(ve(N),Ne(N[0])):(W(N),ne(N[0]))}catch(N){alert((N==null?void 0:N.message)||"获取发货地失败")}finally{m(!1)}},i=>{m(!1),alert(i.code===i.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Lt=n=>o.filter(C=>C.cookie_id===n.cookie_id&&C.item_id===n.item_id).length>0?o.filter(C=>C.cookie_id===n.cookie_id&&C.item_id===n.item_id):o.filter(C=>C.cookie_id===n.cookie_id&&!C.item_id),nt=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},ut=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},et=r.useMemo(()=>new Map(v.map(n=>[n.id,n])),[v]),it=r.useMemo(()=>O?s.filter(n=>n.cookie_id===O):s,[O,s]),Ve=n=>{const C=et.get(n),i=(C==null?void 0:C.remark)||(C==null?void 0:C.nickname);return i?`${i} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},ht=n=>{const C=et.get(n);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",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(el,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:O,onChange:n=>j(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),v.map(n=>e.jsx("option",{value:n.id,children:Ve(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:A,onChange:n=>b(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),v.map(n=>e.jsx("option",{value:n.id,children:Ve(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:Ae,disabled:V||!A,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Be,{className:`w-4 h-4 ${V?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:St,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(Ye,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:lt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Yt,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void re(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-br Line truncated
+1 -1
View File
@@ -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-6YoCxbHU.js"></script>
<script type="module" crossorigin src="/static/assets/index-DhAArJzx.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-DF3hof7q.js">
<link rel="modulepreload" crossorigin href="/static/assets/vendor-D-Edl3pr.js">
@@ -279,12 +279,6 @@ func TestPublishWorkflowUsesCookieSessionForEveryRequest(t *testing.T) {
rotate(w, "token2")
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"c1","catName":"类目"}}}`)
},
"mtop.taobao.idle.local.poi.get": func(w http.ResponseWriter, req *http.Request) {
assertCookies(req, "token2", "api_http_only=api")
assertSign(req, "token2")
rotate(w, "token3")
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"area":"X","city":"Y","divisionId":"1","longitude":118.7,"latitude":31.9,"poiId":"p1","poi":"P","prov":"Z"}]}}`)
},
"mtop.idle.pc.idleitem.publish": func(w http.ResponseWriter, req *http.Request) {
assertCookies(req, "token2", "api_http_only=api")
assertSign(req, "token2")
+6 -58
View File
@@ -24,10 +24,9 @@ import (
)
const (
UploadMediaAPI = "https://stream-upload.goofish.com/api/upload.api"
PublishItemAPI = "https://h5api.m.goofish.com/h5/mtop.idle.pc.idleitem.publish/1.0/"
RecommendItemAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.kgraph.property.recommend/2.0/"
DefaultLocationAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.local.poi.get/1.0/"
UploadMediaAPI = "https://stream-upload.goofish.com/api/upload.api"
PublishItemAPI = "https://h5api.m.goofish.com/h5/mtop.idle.pc.idleitem.publish/1.0/"
RecommendItemAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.kgraph.property.recommend/2.0/"
)
// ErrPublishCategoryUnrecognized 表示闲鱼类目推荐接口调用成功,但没有给出可发布类目。
@@ -73,7 +72,7 @@ type PublishCategory struct {
TBCatID string `json:"tb_cat_id,omitempty"`
}
// PublishLocation 是闲鱼定位接口返回、可直接用于发布商品的发货地。
// PublishLocation 是高德附近 POI 映射成的、可直接用于闲鱼发布商品的发货地。
type PublishLocation struct {
Area string `json:"area"`
City string `json:"city"`
@@ -187,34 +186,6 @@ func (c *ClientImpl) PublishItem(ctx context.Context, cookiesStr string, req Pub
return c.publishItemOnce(ctx, currentCookies, req, uploaded, category)
}
// PublishLocations 根据浏览器提供的真实坐标查询闲鱼可用的发货地。
func (c *ClientImpl) PublishLocations(ctx context.Context, cookiesStr string, longitude, latitude float64) ([]PublishLocation, string, error) {
if longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90 || (longitude == 0 && latitude == 0) {
return nil, cookiesStr, errors.New("经纬度无效")
}
data := map[string]any{"longitude": longitude, "latitude": latitude}
decoded, updated, err := c.callMTop(ctx, cookiesStr, DefaultLocationAPI, "mtop.taobao.idle.local.poi.get", "1.0", "a21ybx.publish.0.0", "a21ybx.item.sidebar.1.38262218ame5nr", "38262218ame5nr", data)
if err != nil {
return nil, updated, err
}
if !hasMTopSuccess(retFromDecoded(decoded)) {
return nil, updated, classifyPublishError(retFromDecoded(decoded), decoded)
}
dataMap := mapFromAny(decoded["data"])
addresses, _ := dataMap["commonAddresses"].([]any)
locations := make([]PublishLocation, 0, len(addresses))
for _, raw := range addresses {
loc := publishLocationFromMap(mapFromAny(raw))
if validPublishLocation(loc) {
locations = append(locations, loc)
}
}
if len(locations) == 0 {
return nil, updated, errors.New("当前位置没有可用的闲鱼发货地,请在闲鱼中完善地址后重试")
}
return locations, updated, nil
}
// RecommendPublishCategory 根据关键词调用闲鱼推荐接口,返回可直接用于发布的完整类目。
func (c *ClientImpl) RecommendPublishCategory(ctx context.Context, cookiesStr, keyword string) (PublishCategory, string, error) {
keyword = strings.TrimSpace(keyword)
@@ -429,34 +400,10 @@ func fallbackPublishCategory(category PublishCategory) map[string]any {
}
}
func publishLocationFromMap(loc map[string]any) PublishLocation {
return PublishLocation{
Area: strings.TrimSpace(mtopString(loc["area"])), City: strings.TrimSpace(mtopString(loc["city"])),
DivisionID: strings.TrimSpace(mtopString(loc["divisionId"])), Longitude: numberFromAny(loc["longitude"]),
Latitude: numberFromAny(loc["latitude"]), POIID: strings.TrimSpace(mtopString(loc["poiId"])),
POIName: strings.TrimSpace(mtopString(loc["poi"])), Province: strings.TrimSpace(mtopString(loc["prov"])),
}
}
func validPublishLocation(loc PublishLocation) bool {
return loc.DivisionID != "" && loc.Province != "" && loc.City != "" && loc.Longitude >= -180 && loc.Longitude <= 180 && loc.Latitude >= -90 && loc.Latitude <= 90 && !(loc.Longitude == 0 && loc.Latitude == 0)
}
func numberFromAny(v any) float64 {
switch n := v.(type) {
case float64:
return n
case json.Number:
f, _ := n.Float64()
return f
case string:
f, _ := strconv.ParseFloat(strings.TrimSpace(n), 64)
return f
default:
return 0
}
}
func (c *ClientImpl) publishItemOnce(ctx context.Context, cookiesStr string, req PublishItemRequest, images []uploadedImage, category map[string]any) (*PublishItemResult, error) {
imagePayloads := make([]any, 0, len(images))
for i, img := range images {
@@ -494,7 +441,8 @@ func (c *ClientImpl) publishItemOnce(ctx context.Context, cookiesStr string, req
}
data["itemAddrDTO"] = map[string]any{
"area": req.Location.Area, "city": req.Location.City, "divisionId": req.Location.DivisionID,
"gps": fmt.Sprintf("%s,%s", strconv.FormatFloat(req.Location.Longitude, 'f', -1, 64), strconv.FormatFloat(req.Location.Latitude, 'f', -1, 64)),
// 闲鱼网页版发布页使用 latitude,longitude 的顺序。
"gps": fmt.Sprintf("%s,%s", strconv.FormatFloat(req.Location.Latitude, 'f', -1, 64), strconv.FormatFloat(req.Location.Longitude, 'f', -1, 64)),
"poiId": req.Location.POIID, "poiName": req.Location.POIName, "prov": req.Location.Province,
}
} else if !req.Virtual {
+7 -50
View File
@@ -16,7 +16,7 @@ import (
"testing"
)
// publish.go 用常量 URL(UploadMediaAPI / RecommendItemAPI / DefaultLocationAPI / PublishItemAPI),
// publish.go 用常量 URL(UploadMediaAPI / RecommendItemAPI / PublishItemAPI),
// 通过 dispatchTransport 按 api query 参数分发到不同本地 handler,覆盖各 mtop 调用路径。
type dispatchTransport struct {
@@ -78,6 +78,7 @@ func TestPublishItemValidationFailures(t *testing.T) {
func TestPublishItemDescriptionDefaultsToTitle(t *testing.T) {
png1 := tinyPNG(t)
var gotDesc string
var publishedData map[string]any
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
@@ -96,10 +97,8 @@ func TestPublishItemDescriptionDefaultsToTitle(t *testing.T) {
}
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"c1","catName":"类目"}}}`)
},
"mtop.taobao.idle.local.poi.get": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"area":"X","city":"Y","divisionId":"1","longitude":118.7,"latitude":31.9,"poiId":"p1","poi":"P","prov":"Z"}]}}`)
},
"mtop.idle.pc.idleitem.publish": func(w http.ResponseWriter, r *http.Request) {
publishedData, _ = parseDataURL(readBody(r))
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"new-item-1"}}`)
},
}}
@@ -129,6 +128,10 @@ func TestPublishItemDescriptionDefaultsToTitle(t *testing.T) {
if res.ImageURL != "https://cdn/a.jpg" {
t.Fatalf("ImageURL=%q", res.ImageURL)
}
addr, ok := publishedData["itemAddrDTO"].(map[string]any)
if !ok || addr["gps"] != "31.9,118.7" {
t.Fatalf("itemAddrDTO=%+v, gps should be latitude,longitude", publishedData["itemAddrDTO"])
}
}
// TestPublishItemUploadImageFailure: 图片上传失败导致 PublishItem 失败。
@@ -221,9 +224,6 @@ func TestPublishItemLocationFailure(t *testing.T) {
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"c1","catName":"类目"}}}`)
},
"mtop.taobao.idle.local.poi.get": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[]}}`)
},
}}
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
req := PublishItemRequest{
@@ -365,9 +365,6 @@ func TestPublishItemFinalPublishFailure(t *testing.T) {
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"c1","catName":"类目"}}}`)
},
"mtop.taobao.idle.local.poi.get": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"area":"X","city":"Y","divisionId":"1","longitude":118.7,"latitude":31.9,"poiId":"p1","poi":"P","prov":"Z"}]}}`)
},
"mtop.idle.pc.idleitem.publish": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXPIRED::令牌过期"]}`)
},
@@ -402,9 +399,6 @@ func TestPublishItemStockPermissionError(t *testing.T) {
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"c1","catName":"类目"}}}`)
},
"mtop.taobao.idle.local.poi.get": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"area":"X","city":"Y","divisionId":"1","longitude":118.7,"latitude":31.9,"poiId":"p1","poi":"P","prov":"Z"}]}}`)
},
"mtop.idle.pc.idleitem.publish": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["账号没有库存发布权限"]}`)
},
@@ -621,43 +615,6 @@ func TestRecommendPublishCategoryEmptyCatId(t *testing.T) {
}
}
// ---- PublishLocations 真实坐标查询测试 ----
func TestPublishLocationsUsesProvidedCoordinates(t *testing.T) {
var requested map[string]any
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"mtop.taobao.idle.local.poi.get": func(w http.ResponseWriter, r *http.Request) {
requested, _ = parseDataURL(readBody(r))
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"area":"A","city":"C","divisionId":"1","longitude":118.7,"latitude":31.9,"poiId":"p","poi":"P","prov":"PR"},{"area":"A","city":"C","divisionId":"1","longitude":118.71,"latitude":31.91,"poiId":"p2","poi":"P2","prov":"PR"}]}}`)
},
}}
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
locations, _, err := client.PublishLocations(context.Background(), consignCookies, 118.7, 31.9)
if err != nil {
t.Fatalf("err=%v", err)
}
if requested["longitude"] != float64(118.7) || requested["latitude"] != float64(31.9) {
t.Fatalf("查询坐标=%+v", requested)
}
if len(locations) != 2 || locations[0].Area != "A" || locations[1].POIID != "p2" {
t.Fatalf("locations=%+v", locations)
}
}
func TestPublishLocationsMalformedAddress(t *testing.T) {
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"mtop.taobao.idle.local.poi.get": func(w http.ResponseWriter, r *http.Request) {
// commonAddresses[0] 不是 map
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":["not-a-map"]}}`)
},
}}
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
_, _, err := client.PublishLocations(context.Background(), consignCookies, 118.7, 31.9)
if err == nil || !strings.Contains(err.Error(), "没有可用") {
t.Fatalf("err=%v", err)
}
}
// ---- callMTop / buildMTopQuery ----
func TestCallMTopParseFailure(t *testing.T) {