feat(商城管理): 客户商品库后台一期

新增 /customers/mall 卡片管理、Excel 导入、上下架/描述/收藏/移出;复用客户销售价接口;修复共享报价单并发改价、i18n、迁移空 schema、并发计数。
This commit is contained in:
Ubuntu
2026-10-28 20:23:43 +08:00
parent 415e5a58c0
commit 94de4e60de
21 changed files with 2230 additions and 19 deletions
+1 -1
View File
@@ -28,7 +28,7 @@ import { useT } from '../i18n';
export interface SmartImportConfig {
/** 导入类型(记忆隔离键) */
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier';
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier' | 'mall_product';
/** 字段词典 */
fields: ImportFieldDef[];
/** 解析 sheet 偏好 */
+1
View File
@@ -36,6 +36,7 @@ export const MENU_CATALOG: MenuCatalogEntry[] = [
},
{ menuKey: 'customers-list', path: '/customers', defaultLabel: '客户列表', icon: 'ChevronRight', permission: 'customer_manage', secondary: true },
{ menuKey: 'customers-quote-versions', path: '/customers/quote-versions', defaultLabel: '报价管理', icon: 'ChevronRight', permission: 'customer_manage', secondary: true },
{ menuKey: 'customers-mall', path: '/customers/mall', defaultLabel: '商城管理', icon: 'Store', permission: 'customer_manage', secondary: true },
{ menuKey: 'products-categories', path: '/products/categories', defaultLabel: '分类管理', icon: 'ChevronRight', permission: ['category_manage', 'product_manage'], secondary: true },
{ menuKey: 'products-skus', path: '/products/skus', defaultLabel: '商品管理', icon: 'ChevronRight', permission: ['sku_manage', 'product_manage'], secondary: true },
{ menuKey: 'products-units', path: '/products/units', defaultLabel: '单位管理', icon: 'ChevronRight', permission: ['sku_manage', 'product_manage'], secondary: true },
+46
View File
@@ -151,4 +151,50 @@ export const customers: MessageDict = {
'toast.importDone': 'Customer import finished',
'toast.unsupportedAction': 'This page does not support action {id}',
'mall.title': 'Mall management',
'mall.customerPlaceholder': 'Select customer',
'mall.searchPlaceholder': 'Search product name or code',
'mall.filter.all': 'All',
'mall.filter.aria': 'Filter products',
'mall.btn.add': 'Add products',
'mall.btn.import': 'Import products',
'mall.btn.remove': 'Remove',
'mall.btn.list': 'List',
'mall.btn.unlist': 'Unlist',
'mall.col.price': 'Mall price',
'mall.col.favorite': 'Favorite',
'mall.col.lastOrder': 'Last order',
'mall.col.product': 'products',
'mall.status.orderable': 'Orderable',
'mall.status.unlisted': 'Unlisted',
'mall.status.missingPrice': 'No price',
'mall.status.skuDisabled': 'Product disabled',
'mall.status.skuMissing': 'Product missing',
'mall.priceTarget.quoteSheet': 'Quote',
'mall.priceTarget.lastSale': 'Last sale',
'mall.priceTarget.library': 'Library',
'mall.empty.noCustomer': 'Select a customer first',
'mall.empty.noItems': 'No products yet. Use Add products or Import products.',
'mall.empty.noMatch': 'No matching products',
'mall.add.title': 'Add products',
'mall.add.searchPlaceholder': 'Search product catalog',
'mall.add.selected': '{n} selected',
'mall.add.empty': 'No products available to add',
'mall.add.unknown': '{n} product codes do not exist or are disabled',
'mall.edit.title': 'Edit product',
'mall.edit.name': 'Customer product name',
'mall.edit.description': 'Description',
'mall.edit.unit': 'Unit',
'mall.edit.price': 'Customer sale price',
'mall.edit.favorite': 'Pin to top in mall',
'mall.remove.title': 'Remove product',
'mall.remove.message': 'Remove {name} from this customer product library? It will no longer be selectable in the mall or order entry.',
'mall.remove.confirm': 'Remove',
'mall.toast.added': '{n} products added',
'mall.toast.saved': 'Saved',
'mall.toast.removed': 'Removed',
'mall.import.title': 'Import products',
'mall.import.description': 'Fill in product codes from the template to import into {name} customer library. Existing products are skipped.',
'mall.import.templateHint': 'Template: Product code* / Customer product name / Unit / Favorite',
'mall.summary': '{total} products · {orderable} orderable',
};
+1
View File
@@ -50,4 +50,5 @@ export const menu: MessageDict = {
'group.grp-business': 'Operations',
'group.grp-finance': 'Finance',
'group.grp-system': 'System',
'customers-mall': 'Mall management',
};
+46
View File
@@ -152,4 +152,50 @@ export const customers: MessageDict = {
'toast.importDone': 'Impor pelanggan selesai',
'toast.unsupportedAction': 'Halaman ini tidak mendukung aksi {id}',
'mall.title': 'Manajemen toko',
'mall.customerPlaceholder': 'Pilih pelanggan',
'mall.searchPlaceholder': 'Cari nama atau kode produk',
'mall.filter.all': 'Semua',
'mall.filter.aria': 'Saring produk',
'mall.btn.add': 'Tambah produk',
'mall.btn.import': 'Impor produk',
'mall.btn.remove': 'Keluarkan',
'mall.btn.list': 'Tampilkan',
'mall.btn.unlist': 'Sembunyikan',
'mall.col.price': 'Harga toko',
'mall.col.favorite': 'Favorit',
'mall.col.lastOrder': 'Pesanan terakhir',
'mall.col.product': 'produk',
'mall.status.orderable': 'Bisa dipesan',
'mall.status.unlisted': 'Tidak ditampilkan',
'mall.status.missingPrice': 'Belum ada harga',
'mall.status.skuDisabled': 'Produk nonaktif',
'mall.status.skuMissing': 'Produk tidak ada',
'mall.priceTarget.quoteSheet': 'Penawaran',
'mall.priceTarget.lastSale': 'Penjualan terakhir',
'mall.priceTarget.library': 'Pustaka',
'mall.empty.noCustomer': 'Pilih pelanggan terlebih dahulu',
'mall.empty.noItems': 'Belum ada produk. Gunakan Tambah produk atau Impor produk.',
'mall.empty.noMatch': 'Tidak ada produk yang cocok',
'mall.add.title': 'Tambah produk',
'mall.add.searchPlaceholder': 'Cari katalog produk',
'mall.add.selected': '{n} dipilih',
'mall.add.empty': 'Tidak ada produk yang bisa ditambahkan',
'mall.add.unknown': '{n} kode produk tidak ada atau nonaktif',
'mall.edit.title': 'Edit produk',
'mall.edit.name': 'Nama produk pelanggan',
'mall.edit.description': 'Deskripsi',
'mall.edit.unit': 'Satuan',
'mall.edit.price': 'Harga jual pelanggan',
'mall.edit.favorite': 'Sematkan di atas toko',
'mall.remove.title': 'Keluarkan produk',
'mall.remove.message': 'Keluarkan {name} dari pustaka produk pelanggan ini? Produk tidak bisa dipilih lagi di toko maupun entri pesanan.',
'mall.remove.confirm': 'Keluarkan',
'mall.toast.added': '{n} produk ditambahkan',
'mall.toast.saved': 'Tersimpan',
'mall.toast.removed': 'Dikeluarkan',
'mall.import.title': 'Impor produk',
'mall.import.description': 'Isi kode produk sesuai templat untuk mengimpor ke pustaka pelanggan {name}. Produk yang sudah ada akan dilewati.',
'mall.import.templateHint': 'Templat: Kode produk* / Nama produk pelanggan / Satuan / Favorit',
'mall.summary': '{total} produk · {orderable} bisa dipesan',
};
+1
View File
@@ -50,4 +50,5 @@ export const menu: MessageDict = {
'group.grp-business': 'Operasi',
'group.grp-finance': 'Keuangan',
'group.grp-system': 'Sistem',
'customers-mall': 'Manajemen toko',
};
+46
View File
@@ -151,4 +151,50 @@ export const customers: MessageDict = {
'toast.importDone': '客户批量导入完成',
'toast.unsupportedAction': '当前页不支持操作 {id}',
'mall.title': '商城管理',
'mall.customerPlaceholder': '选择客户',
'mall.searchPlaceholder': '搜索商品名或编码',
'mall.filter.all': '全部',
'mall.filter.aria': '筛选商品',
'mall.btn.add': '添加商品',
'mall.btn.import': '导入商品',
'mall.btn.remove': '移出',
'mall.btn.list': '上架',
'mall.btn.unlist': '下架',
'mall.col.price': '商城价',
'mall.col.favorite': '收藏',
'mall.col.lastOrder': '最近下单',
'mall.col.product': '商品',
'mall.status.orderable': '可下单',
'mall.status.unlisted': '已下架',
'mall.status.missingPrice': '待报价',
'mall.status.skuDisabled': '档案停用',
'mall.status.skuMissing': '档案缺失',
'mall.priceTarget.quoteSheet': '报价单',
'mall.priceTarget.lastSale': '上次成交',
'mall.priceTarget.library': '商品库',
'mall.empty.noCustomer': '请先选择客户',
'mall.empty.noItems': '暂无商品,点击「添加商品」或「导入商品」',
'mall.empty.noMatch': '没有匹配的商品',
'mall.add.title': '添加商品',
'mall.add.searchPlaceholder': '搜索商品档案',
'mall.add.selected': '已选 {n} 个',
'mall.add.empty': '没有可添加的商品',
'mall.add.unknown': '{n} 个商品编码不存在或已停用',
'mall.edit.title': '编辑商品',
'mall.edit.name': '客户商品名',
'mall.edit.description': '描述',
'mall.edit.unit': '单位',
'mall.edit.price': '客户销售价',
'mall.edit.favorite': '收藏到商城前排',
'mall.remove.title': '移出商品',
'mall.remove.message': '将「{name}」从该客户商品库移除?商城与录单都将不可再选。',
'mall.remove.confirm': '移出',
'mall.toast.added': '已添加 {n} 个商品',
'mall.toast.saved': '已保存',
'mall.toast.removed': '已移出',
'mall.import.title': '导入商品',
'mall.import.description': '按模板填写商品编码,导入到「{name}」的客户商品库。已在库中的商品会跳过。',
'mall.import.templateHint': '模板列:商品编码* / 客户商品名 / 单位 / 收藏',
'mall.summary': '共 {total} 个商品 · 可下单 {orderable}',
};
+1
View File
@@ -50,4 +50,5 @@ export const menu: MessageDict = {
'group.grp-business': '业务流程',
'group.grp-finance': '财务管理',
'group.grp-system': '系统管理',
'customers-mall': '商城管理',
};
+2 -1
View File
@@ -72,7 +72,7 @@ export const BUSINESS_MODULES: BusinessModuleDef[] = [
id: 'customer',
name: '客户管理',
permissions: ['customer_manage', 'alias_manage'],
menuKeys: ['customers-list', 'customers-quote-versions'],
menuKeys: ['customers-list', 'customers-quote-versions', 'customers-mall'],
routes: [
{
path: 'customers',
@@ -81,6 +81,7 @@ export const BUSINESS_MODULES: BusinessModuleDef[] = [
{ path: '', page: 'CustomerManagement', permission: 'customer_manage' },
{ path: 'alias-library', page: 'CustomerManagement', permission: ['customer_manage', 'alias_manage'], redirect: '/customers/quote-versions?view=library' },
{ path: 'quote-versions', page: 'QuoteVersionManagement', permission: 'customer_manage' },
{ path: 'mall', page: 'MallManagement', permission: 'customer_manage' },
],
},
],
+1
View File
@@ -21,6 +21,7 @@ const PAGE_LOADERS: Record<string, ReturnType<typeof lazyPage>> = {
UnitManagement: lazyPage(() => import('../pages/products/UnitManagement'), 'UnitManagement'),
CustomerManagement: lazyPage(() => import('../pages/customers/CustomerManagement'), 'CustomerManagement'),
QuoteVersionManagement: lazyPage(() => import('../pages/customers/QuoteVersionManagement'), 'QuoteVersionManagement'),
MallManagement: lazyPage(() => import('../pages/customers/MallManagement'), 'MallManagement'),
SupplierManagement: lazyPage(() => import('../pages/suppliers/SupplierManagement'), 'SupplierManagement'),
OrderManagement: lazyPage(() => import('../pages/orders/orderManagement'), 'OrderManagement'),
OrderTrash: lazyPage(() => import('../pages/orders/OrderTrash'), 'OrderTrash'),
+861
View File
@@ -0,0 +1,861 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
Loader2,
Package,
Plus,
RefreshCw,
Search,
Star,
Trash2,
Upload,
} from 'lucide-react';
import { supabase } from '../../supabase/client';
import { useOperatingBranch } from '../../hooks/useOperatingBranch';
import { useT } from '../../i18n';
import { SearchableSelect } from '../../components/ui/SearchableSelect';
import { DialogOverlay } from '../../components/ui/DialogOverlay';
import { BulkImportModal } from '../../components/BulkImportModal';
import { TablePaginationBar } from '../../components/ui/TablePaginationBar';
import { useClientTablePagination } from '../../hooks/useClientTablePagination';
import { notify } from '../../utils/notify';
import { confirmDialog } from '../../utils/confirmDialog';
import { resolveSkuImageUrl } from '../../utils/skuImage';
import {
MALL_IMPORT_FIELD_DICT,
downloadMallImportTemplate,
mapMallImportRows,
} from '../../utils/customerMallImport';
import {
addMallLibrarySkusApi,
fetchMallLibraryApi,
importMallRowsApi,
previewMallImportApi,
removeMallLibrarySkuApi,
searchMallCatalogApi,
setCustomerSkuSalePriceApi,
updateMallLibraryItemApi,
type MallCatalogSku,
type MallLibraryItem,
type MallLibraryStatus,
} from '../../utils/workflowApi';
type CustomerOption = {
customer_code: string;
company_name: string;
branch_code: string | null;
status: number | null;
};
type MallLibraryState = {
customer: { customer_code: string; company_name: string; branch_code: string | null };
items: MallLibraryItem[];
summary: Record<MallLibraryStatus, number> & { total: number };
};
const TRADABLE_STATUS = new Set([1, 10, 20, 30]);
// 卡片内原位输入框:普通灰边框(不用主题色 focus 外框,2026-10-30 开发者要求)。
const INLINE_INPUT_CLASS =
'h-7 rounded-md border border-slate-200 bg-white px-1.5 text-[13px] text-slate-800 transition-colors hover:border-slate-300 focus:border-slate-400 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100';
type MallCardProps = {
item: MallLibraryItem;
customerCode: string;
listing: boolean;
onToggleListed: (item: MallLibraryItem) => void;
onRemove: (item: MallLibraryItem) => void;
onRefresh: () => Promise<void>;
};
/** 卡片内直接编辑:输入框就在显示位置,失焦/回车即保存(无编辑按钮、无 ✓/×)。 */
const MallCard: React.FC<MallCardProps> = ({
item,
customerCode,
listing,
onToggleListed,
onRemove,
onRefresh,
}) => {
const t = useT();
const statusMeta: Record<MallLibraryStatus, { label: string; cls: string }> = {
orderable: { label: t('customers.mall.status.orderable'), cls: 'app-status-success' },
missing_price: { label: t('customers.mall.status.missingPrice'), cls: 'app-status-warning' },
sku_disabled: { label: t('customers.mall.status.skuDisabled'), cls: 'app-status-danger' },
sku_missing: { label: t('customers.mall.status.skuMissing'), cls: 'app-status-danger' },
};
const meta = statusMeta[item.status];
const imageSrc = resolveSkuImageUrl(item.image_url, item.sku_code);
// 展示名与档案名一致时输入框留空(placeholder 显示档案名),保存空值 = 沿用档案名。
const editableName = (value: string) =>
item.catalog_name && value === item.catalog_name ? '' : value;
const initialPrice =
item.mall_price > 0
? item.mall_price
: item.sale_price != null && item.sale_price > 0
? item.sale_price
: null;
const saved = useRef({
name: editableName(String(item.display_name || '')),
description: String(item.description || ''),
unit: String(item.unit || ''),
price: initialPrice as number | null,
});
const [name, setName] = useState(saved.current.name);
const [description, setDescription] = useState(saved.current.description);
const [unit, setUnit] = useState(saved.current.unit);
const [price, setPrice] = useState(initialPrice != null ? initialPrice.toFixed(2) : '');
const [favorite, setFavorite] = useState(item.is_favorite);
const [pending, setPending] = useState(0);
const priceDirty = useRef(false);
const busy = pending > 0;
// 价格可能由报价单决定:服务端刷新后用生效价回填,但不打断正在输入的值。
useEffect(() => {
if (priceDirty.current) return;
const next =
item.mall_price > 0
? item.mall_price
: item.sale_price != null && item.sale_price > 0
? item.sale_price
: null;
saved.current.price = next;
setPrice(next != null ? next.toFixed(2) : '');
}, [item.mall_price, item.sale_price]);
const fail = (error: any) => notify.error(error?.message || t('customers.toast.saveFail'));
const patchFields = async (patch: {
customer_sku_name?: string | null;
description?: string | null;
customer_unit?: string | null;
}): Promise<boolean> => {
if (!Object.keys(patch).length) return true;
setPending((n) => n + 1);
try {
await updateMallLibraryItemApi(customerCode, item.sku_code, patch);
return true;
} catch (error: any) {
fail(error);
return false;
} finally {
setPending((n) => n - 1);
}
};
const commitName = async () => {
const next = name.trim();
if (next === saved.current.name.trim()) return;
if (await patchFields({ customer_sku_name: next || null })) {
saved.current.name = next;
setName(next);
await onRefresh();
} else {
setName(saved.current.name);
}
};
const commitDescription = async () => {
const next = description.trim();
if (next === saved.current.description.trim()) return;
if (await patchFields({ description: next || null })) {
saved.current.description = next;
setDescription(next);
await onRefresh();
} else {
setDescription(saved.current.description);
}
};
const commitUnit = async () => {
const next = unit.trim();
if (next === saved.current.unit.trim()) return;
if (await patchFields({ customer_unit: next || null })) {
saved.current.unit = next;
setUnit(next);
await onRefresh();
} else {
setUnit(saved.current.unit);
}
};
const commitPrice = async () => {
const raw = price.trim();
const next = raw === '' ? null : Number(raw);
if (next != null && (!Number.isFinite(next) || next < 0)) {
fail(new Error(t('customers.toast.saveFail')));
setPrice(saved.current.price != null ? saved.current.price.toFixed(2) : '');
return;
}
const normalized = next != null && next > 0 ? next : null;
if (normalized === saved.current.price) {
priceDirty.current = false;
setPrice(saved.current.price != null ? saved.current.price.toFixed(2) : '');
return;
}
setPending((n) => n + 1);
try {
// 改价复用既有入口:执行中报价单里有该商品 → 写报价单条目;
// 没有报价单 → 写客户商品库。
await setCustomerSkuSalePriceApi({
customerCode,
sku_code: item.sku_code,
sale_price: normalized,
});
saved.current.price = normalized;
priceDirty.current = false;
await onRefresh();
} catch (error: any) {
fail(error);
setPrice(saved.current.price != null ? saved.current.price.toFixed(2) : '');
} finally {
setPending((n) => n - 1);
}
};
const toggleFavorite = async () => {
const next = !favorite;
setFavorite(next);
setPending((n) => n + 1);
try {
await updateMallLibraryItemApi(customerCode, item.sku_code, { is_favorite: next });
} catch (error: any) {
setFavorite(!next);
fail(error);
} finally {
setPending((n) => n - 1);
}
};
const commitOnEnter = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter') event.currentTarget.blur();
};
return (
<div className="flex gap-1.5 overflow-hidden rounded-lg border border-slate-200 bg-white p-2 dark:border-slate-700 dark:bg-slate-900">
<div className="relative w-20 shrink-0 self-stretch overflow-hidden rounded-md bg-slate-100 dark:bg-slate-800">
{imageSrc ? (
<img
src={imageSrc}
alt={item.display_name}
loading="lazy"
className="h-full w-full object-cover"
/>
) : (
<div className="flex h-full w-full items-center justify-center">
<Package className="h-4 w-4 text-slate-300 dark:text-slate-600" />
</div>
)}
<button
type="button"
className={`absolute bottom-0.5 right-0.5 rounded p-0.5 hover:bg-white/70 disabled:opacity-50 dark:hover:bg-slate-800 ${
favorite ? 'text-amber-500' : 'text-slate-400'
}`}
title={t('customers.mall.col.favorite')}
aria-label={t('customers.mall.col.favorite')}
disabled={busy}
onClick={() => void toggleFavorite()}
>
<Star className="h-3 w-3" fill={favorite ? 'currentColor' : 'none'} />
</button>
</div>
<div className="flex min-w-0 flex-1 flex-col justify-center gap-1">
<div className="flex items-center gap-1">
<span
className={`shrink-0 whitespace-nowrap rounded-full px-1.5 py-0.5 text-xs ${
item.is_listed
? meta.cls
: 'bg-slate-200 text-slate-600 dark:bg-slate-700 dark:text-slate-300'
}`}
>
{item.is_listed ? meta.label : t('customers.mall.status.unlisted')}
</span>
<input
className={`${INLINE_INPUT_CLASS} min-w-0 flex-1`}
style={{ outline: 'none' }}
value={name}
onChange={(event) => setName(event.target.value)}
onBlur={() => void commitName()}
onKeyDown={commitOnEnter}
placeholder={item.catalog_name || item.display_name}
aria-label={t('customers.mall.edit.name')}
/>
<button
type="button"
className="shrink-0 whitespace-nowrap rounded-md border border-slate-200 px-1.5 py-0.5 text-[13px] text-slate-800 transition-colors hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-100 dark:hover:bg-slate-800"
disabled={listing}
onClick={() => onToggleListed(item)}
>
{listing
? '…'
: item.is_listed
? t('customers.mall.btn.unlist')
: t('customers.mall.btn.list')}
</button>
<button
type="button"
className="shrink-0 rounded p-0.5 text-slate-500 hover:bg-slate-100 hover:text-rose-600 dark:hover:bg-slate-800 dark:hover:text-rose-400"
title={t('customers.mall.btn.remove')}
aria-label={t('customers.mall.btn.remove')}
onClick={() => onRemove(item)}
>
<Trash2 className="h-3.5 w-3.5" />
</button>
{busy ? <Loader2 className="h-3 w-3 shrink-0 animate-spin text-slate-400" /> : null}
</div>
<div className="flex items-center gap-1">
<span className="text-[13px] text-slate-800 dark:text-slate-100">¥</span>
<input
type="number"
min="0"
step="0.01"
className={`${INLINE_INPUT_CLASS} min-w-0 flex-1 appearance-none text-right tabular-nums [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none`}
style={{ outline: 'none' }}
value={price}
onChange={(event) => {
priceDirty.current = true;
setPrice(event.target.value);
}}
onBlur={() => void commitPrice()}
onKeyDown={commitOnEnter}
placeholder="—"
aria-label={t('customers.mall.edit.price')}
/>
<input
className={`${INLINE_INPUT_CLASS} w-[4.5rem] shrink-0 px-1 text-center`}
style={{ outline: 'none' }}
value={unit}
onChange={(event) => setUnit(event.target.value)}
onBlur={() => void commitUnit()}
onKeyDown={commitOnEnter}
placeholder={item.catalog_unit || '斤'}
aria-label={t('customers.mall.edit.unit')}
/>
<span className="shrink-0 whitespace-nowrap rounded-md border border-slate-200 px-1.5 text-[13px] leading-7 text-slate-800 dark:border-slate-700 dark:text-slate-100">
{item.price_source === 'quote_sheet' || item.on_quote_sheet
? t('customers.mall.priceTarget.quoteSheet')
: item.price_source === 'last_sale_name_spec'
? t('customers.mall.priceTarget.lastSale')
: t('customers.mall.priceTarget.library')}
</span>
</div>
<input
className={`${INLINE_INPUT_CLASS} w-full`}
style={{ outline: 'none' }}
value={description}
onChange={(event) => setDescription(event.target.value)}
onBlur={() => void commitDescription()}
onKeyDown={commitOnEnter}
placeholder={t('customers.mall.edit.description')}
aria-label={t('customers.mall.edit.description')}
/>
</div>
</div>
);
}
export const MallManagement: React.FC = () => {
const t = useT();
const { operatingBranchCode } = useOperatingBranch();
const [searchParams, setSearchParams] = useSearchParams();
const [customers, setCustomers] = useState<CustomerOption[]>([]);
const [customerCode, setCustomerCode] = useState('');
const [library, setLibrary] = useState<MallLibraryState | null>(null);
const [loading, setLoading] = useState(false);
const [query, setQuery] = useState('');
const [sourceFilter, setSourceFilter] = useState<'all' | 'missing_price' | 'library' | 'quote_sheet'>('all');
const [addOpen, setAddOpen] = useState(false);
const [catalogQuery, setCatalogQuery] = useState('');
const [catalog, setCatalog] = useState<MallCatalogSku[]>([]);
const [catalogLoading, setCatalogLoading] = useState(false);
const [selectedCodes, setSelectedCodes] = useState<string[]>([]);
const [adding, setAdding] = useState(false);
const [listingSku, setListingSku] = useState<string | null>(null);
const [importOpen, setImportOpen] = useState(false);
const catalogTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const initialCustomerRef = useRef(String(searchParams.get('customer') || '').trim());
useEffect(() => {
let cancelled = false;
void (async () => {
const { data } = await supabase
.from('customers')
.select('customer_code, company_name, branch_code, status')
.order('company_name', { ascending: true });
if (cancelled) return;
const rows = ((data || []) as CustomerOption[]).filter((row) =>
TRADABLE_STATUS.has(Number(row.status ?? 10))
);
setCustomers(rows);
const fromUrl = initialCustomerRef.current;
setCustomerCode((prev) => {
if (prev && rows.some((row) => row.customer_code === prev)) return prev;
if (fromUrl && rows.some((row) => row.customer_code === fromUrl)) return fromUrl;
return rows[0]?.customer_code || '';
});
})();
return () => {
cancelled = true;
};
// 只在切分公司时重拉客户列表;URL 上的 customer 只用于首次定位
}, [operatingBranchCode]);
useEffect(() => {
if (!customerCode) {
setLibrary(null);
return;
}
setSearchParams(
(prev) => {
const next = new URLSearchParams(prev);
next.set('customer', customerCode);
return next;
},
{ replace: true }
);
}, [customerCode, setSearchParams]);
const loadLibrary = useCallback(async (options?: { silent?: boolean }) => {
if (!customerCode) return;
if (!options?.silent) setLoading(true);
try {
const res = await fetchMallLibraryApi(customerCode);
setLibrary(res.data);
} catch (error: any) {
notify.error(error?.message || t('customers.mall.empty.noCustomer'));
setLibrary(null);
} finally {
if (!options?.silent) setLoading(false);
}
}, [customerCode, t]);
useEffect(() => {
void loadLibrary();
}, [loadLibrary]);
const customerOptions = useMemo(
() =>
customers.map((row) => ({
value: row.customer_code,
label: row.company_name || row.customer_code,
})),
[customers]
);
const filteredItems = useMemo(() => {
const q = query.trim().toLowerCase();
let items = library?.items || [];
if (sourceFilter === 'missing_price') {
items = items.filter((item) => item.status === 'missing_price');
} else if (sourceFilter === 'library') {
items = items.filter((item) => !item.on_quote_sheet);
} else if (sourceFilter === 'quote_sheet') {
items = items.filter((item) => Boolean(item.on_quote_sheet));
}
if (!q) return items;
return items.filter(
(item) =>
item.display_name.toLowerCase().includes(q) ||
item.sku_code.toLowerCase().includes(q) ||
String(item.catalog_name || '').toLowerCase().includes(q)
);
}, [library, query, sourceFilter]);
const page = useClientTablePagination(filteredItems, {
resetKey: `${customerCode}|${query}|${sourceFilter}`,
});
const loadCatalog = useCallback(
async (q: string) => {
if (!customerCode) return;
setCatalogLoading(true);
try {
const res = await searchMallCatalogApi(customerCode, q);
setCatalog(res.data || []);
} catch (error: any) {
notify.error(error?.message || t('customers.mall.add.empty'));
setCatalog([]);
} finally {
setCatalogLoading(false);
}
},
[customerCode, t]
);
const openAdd = () => {
if (!customerCode) return;
setAddOpen(true);
setCatalogQuery('');
setSelectedCodes([]);
void loadCatalog('');
};
const onCatalogQueryChange = (value: string) => {
setCatalogQuery(value);
if (catalogTimer.current) clearTimeout(catalogTimer.current);
catalogTimer.current = setTimeout(() => {
catalogTimer.current = null;
void loadCatalog(value);
}, 300);
};
const toggleCatalogSku = (skuCode: string) => {
setSelectedCodes((prev) =>
prev.includes(skuCode) ? prev.filter((code) => code !== skuCode) : [...prev, skuCode]
);
};
const submitAdd = async () => {
if (!customerCode || !selectedCodes.length || adding) return;
setAdding(true);
try {
const res = await addMallLibrarySkusApi(customerCode, selectedCodes);
const data = res.data;
notify.success(
t('customers.mall.toast.added', { n: String(data.added) })
);
if (data.unknown?.length) {
notify.warning(t('customers.mall.add.unknown', { n: String(data.unknown.length) }));
}
setAddOpen(false);
setSelectedCodes([]);
await loadLibrary();
} catch (error: any) {
notify.error(error?.message || t('customers.mall.add.title'));
} finally {
setAdding(false);
}
};
const toggleListed = async (item: MallLibraryItem) => {
if (!customerCode || listingSku) return;
setListingSku(item.sku_code);
try {
await updateMallLibraryItemApi(customerCode, item.sku_code, {
is_listed: !item.is_listed,
});
await loadLibrary();
} catch (error: any) {
notify.error(error?.message || t('customers.toast.saveFail'));
} finally {
setListingSku(null);
}
};
const removeItem = async (item: MallLibraryItem) => {
if (!customerCode) return;
const ok = await confirmDialog({
title: t('customers.mall.remove.title'),
message: t('customers.mall.remove.message', { name: item.display_name }),
confirmText: t('customers.mall.remove.confirm'),
danger: true,
});
if (!ok) return;
try {
await removeMallLibrarySkuApi(customerCode, item.sku_code);
notify.success(t('customers.mall.toast.removed'));
await loadLibrary();
} catch (error: any) {
notify.error(error?.message || t('customers.mall.remove.title'));
}
};
return (
<div className="space-y-4">
<div className="app-surface rounded-xl p-4">
<div className="flex items-center gap-2 overflow-x-auto">
{library ? (
<p className="app-foreground-muted shrink-0 whitespace-nowrap text-[12px]">
{t('customers.mall.summary', {
total: String(library.summary.total),
orderable: String(library.summary.orderable),
})}
</p>
) : null}
<div className="w-56 shrink-0">
<SearchableSelect
value={customerCode}
onChange={(value) => {
setCustomerCode(value);
setQuery('');
setSourceFilter('all');
}}
options={customerOptions}
placeholder={t('customers.mall.customerPlaceholder')}
hideSearchIcon
portal
/>
</div>
<div className="relative min-w-[180px] flex-1">
<Search className="app-foreground-muted pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2" />
<input
className="app-input w-full pl-9"
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={t('customers.mall.searchPlaceholder')}
/>
</div>
<div className="flex shrink-0 items-center gap-2" role="group" aria-label={t('customers.mall.filter.aria')}>
{(
[
['all', t('customers.mall.filter.all')],
['missing_price', t('customers.mall.status.missingPrice')],
['library', t('customers.mall.priceTarget.library')],
['quote_sheet', t('customers.mall.priceTarget.quoteSheet')],
] as const
).map(([value, label]) => {
const active = sourceFilter === value;
return (
<button
key={value}
type="button"
aria-pressed={active}
className={`rounded-lg border px-3 py-1.5 text-sm transition-colors ${
active ? 'app-button-primary border-transparent' : 'app-button-secondary app-border'
}`}
onClick={() => setSourceFilter(value)}
>
{label}
</button>
);
})}
</div>
<div className="ml-auto flex shrink-0 items-center gap-2">
<button
type="button"
className="app-button-secondary inline-flex items-center gap-1.5 rounded-lg border px-3 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
onClick={() => void loadLibrary()}
disabled={!customerCode || loading}
>
<RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
{t('common.refresh')}
</button>
<button
type="button"
className="app-button-secondary inline-flex items-center gap-1.5 rounded-lg border px-3 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
onClick={() => setImportOpen(true)}
disabled={!customerCode}
>
<Upload className="h-4 w-4" />
{t('customers.mall.btn.import')}
</button>
<button
type="button"
className="app-button-primary inline-flex items-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
onClick={openAdd}
disabled={!customerCode}
>
<Plus className="h-4 w-4" />
{t('customers.mall.btn.add')}
</button>
</div>
</div>
</div>
<div className="app-surface overflow-hidden rounded-xl">
{!customerCode ? (
<div className="app-foreground-muted px-4 py-16 text-center text-sm">
{t('customers.mall.empty.noCustomer')}
</div>
) : loading && !library ? (
<div className="app-foreground-muted flex items-center justify-center gap-2 px-4 py-16 text-sm">
<Loader2 className="h-4 w-4 animate-spin" />
{t('common.loading')}
</div>
) : filteredItems.length === 0 ? (
<div className="app-foreground-muted px-4 py-16 text-center text-sm">
{library?.items.length
? t('customers.mall.empty.noMatch')
: t('customers.mall.empty.noItems')}
</div>
) : (
<div>
<div
className="grid gap-2 p-2"
style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))' }}
>
{page.pageRows.map((item) => (
<MallCard
key={`${customerCode}:${item.sku_code}`}
item={item}
customerCode={customerCode}
listing={listingSku === item.sku_code}
onToggleListed={(row) => void toggleListed(row)}
onRemove={(row) => void removeItem(row)}
onRefresh={() => loadLibrary({ silent: true })}
/>
))}
</div>
<TablePaginationBar
total={page.total}
page={page.page}
pageSize={page.pageSize}
onPageChange={page.setPage}
onPageSizeChange={page.setPageSize}
itemLabel={t('customers.mall.col.product')}
/>
</div>
)}
</div>
{addOpen ? (
<DialogOverlay>
<div className="flex max-h-[80vh] w-full max-w-2xl flex-col rounded-xl bg-white shadow-xl dark:bg-slate-900">
<div className="flex items-center justify-between border-b border-slate-200 px-4 py-3 dark:border-slate-700">
<h2 className="text-lg font-semibold">{t('customers.mall.add.title')}</h2>
<button
type="button"
className="rounded-md px-2 text-xl leading-none text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800"
onClick={() => setAddOpen(false)}
aria-label={t('common.close')}
>
×
</button>
</div>
<div className="border-b border-slate-200 px-4 py-3 dark:border-slate-700">
<div className="relative">
<Search className="app-foreground-muted pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2" />
<input
className="app-input w-full pl-9"
value={catalogQuery}
onChange={(event) => onCatalogQueryChange(event.target.value)}
placeholder={t('customers.mall.add.searchPlaceholder')}
autoFocus
/>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-2 py-2">
{catalogLoading ? (
<div className="app-foreground-muted flex items-center justify-center gap-2 py-12 text-sm">
<Loader2 className="h-4 w-4 animate-spin" />
{t('common.loading')}
</div>
) : catalog.length === 0 ? (
<div className="app-foreground-muted py-12 text-center text-sm">
{t('customers.mall.add.empty')}
</div>
) : (
catalog.map((sku) => {
const checked = selectedCodes.includes(sku.sku_code);
return (
<label
key={sku.sku_code}
className="flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2 hover:bg-slate-50 dark:hover:bg-slate-800"
>
<input
type="checkbox"
checked={checked}
onChange={() => toggleCatalogSku(sku.sku_code)}
/>
{resolveSkuImageUrl(sku.image_url, sku.sku_code) ? (
<img
src={resolveSkuImageUrl(sku.image_url, sku.sku_code)}
alt={sku.sku_name}
loading="lazy"
className="h-10 w-10 shrink-0 rounded-lg object-cover"
/>
) : (
<span className="h-10 w-10 shrink-0 rounded-lg bg-slate-100 dark:bg-slate-800" />
)}
<span className="min-w-0 flex-1">
<span className="block truncate font-medium">{sku.sku_name}</span>
<span className="app-foreground-muted block truncate text-xs">
{sku.sku_code}
{sku.spec ? ` · ${sku.spec}` : ''}
{sku.unit ? ` · ${sku.unit}` : ''}
</span>
</span>
</label>
);
})
)}
</div>
<div className="flex items-center justify-between gap-3 border-t border-slate-200 px-4 py-3 dark:border-slate-700">
<span className="app-foreground-muted text-sm">
{t('customers.mall.add.selected', { n: String(selectedCodes.length) })}
</span>
<div className="flex items-center gap-2">
<button
type="button"
className="app-button-secondary inline-flex items-center justify-center rounded-lg border px-3 py-2 text-sm font-medium transition-colors"
onClick={() => setAddOpen(false)}
>
{t('common.cancel')}
</button>
<button
type="button"
className="app-button-primary inline-flex items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
onClick={() => void submitAdd()}
disabled={!selectedCodes.length || adding}
>
{adding ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
{t('customers.mall.btn.add')}
</button>
</div>
</div>
</div>
</DialogOverlay>
) : null}
{customerCode ? (
<BulkImportModal
open={importOpen}
title={t('customers.mall.import.title')}
description={t('customers.mall.import.description', {
name: library?.customer.company_name || customerCode,
})}
templateHint={t('customers.mall.import.templateHint')}
onClose={() => setImportOpen(false)}
onDownloadTemplate={downloadMallImportTemplate}
stepFeatures={[
t('bulkImport.features.autoMap'),
t('bulkImport.features.examples'),
t('bulkImport.features.formats'),
]}
maxRowsHint={2000}
onPreview={async (_file, preMapped) => {
const res = await previewMallImportApi(customerCode, mapMallImportRows(preMapped));
const data = res.data;
return {
rowCount: data.total,
willCreate: data.will_create,
willSkip: data.will_skip,
willFail: data.will_fail,
sampleCreates: data.sample_creates,
errors: data.errors,
};
}}
onImport={async (_file, preMapped) => {
const res = await importMallRowsApi(customerCode, mapMallImportRows(preMapped));
const data = res.data;
return {
success: data.created,
skipped: data.skipped,
failed: data.failed,
errors: data.errors,
};
}}
smartImport={{
importType: 'mall_product',
fields: MALL_IMPORT_FIELD_DICT,
preferredSheetNames: ['商城商品'],
requiredHeaderHints: ['商品编码'],
}}
onComplete={() => {
setImportOpen(false);
void loadLibrary();
}}
/>
) : null}
</div>
);
};
export default MallManagement;
+79
View File
@@ -0,0 +1,79 @@
import { downloadExcelTemplate, getCell } from './excelImportExport';
import type { ImportFieldDef } from './smartColumnMapping';
import type { MallImportRow } from './workflowApi';
/**
* 商城管理 · 客户商品库导入(2026-10-29)
*
* 只导入「商品编码 + 可选展示字段」:商品档案本身必须在「商品管理」里已存在,
* 本导入不新建商品档案、不写价格。
*/
export const MALL_IMPORT_HEADERS = ['商品编码*', '客户商品名', '单位', '收藏'];
export const MALL_IMPORT_EXAMPLES: (string | number)[][] = [['SKU00000001', '客户叫法', '斤', '是']];
export const MALL_IMPORT_FIELD_DICT: ImportFieldDef[] = [
{
key: 'skuCode',
label: '商品编码',
required: true,
templateHeader: '商品编码*',
aliases: ['商品编码', '商品代码', '商品编号', 'sku编码', 'sku'],
patterns: [/商品.*(编码|代码|编号)|sku/i],
},
{
key: 'customerSkuName',
label: '客户商品名',
templateHeader: '客户商品名',
aliases: ['客户商品名', '商品名称', '品名', '客户叫法', '名称'],
patterns: [/客户.*名|商品名|品名/],
},
{
key: 'customerUnit',
label: '单位',
templateHeader: '单位',
aliases: ['单位', 'unit'],
patterns: [/单位|unit/i],
},
{
key: 'isFavorite',
label: '收藏',
templateHeader: '收藏',
aliases: ['收藏', '常用', 'is_favorite'],
patterns: [/收藏|常用/],
},
];
export async function downloadMallImportTemplate() {
await downloadExcelTemplate(
'商城商品导入模板.xlsx',
'商城商品',
MALL_IMPORT_HEADERS,
MALL_IMPORT_EXAMPLES,
[
{
name: '填写说明',
headers: ['字段', '说明'],
rows: [
['商品编码*', '必填,必须是本分公司已启用的商品档案编码(sku_code)'],
['客户商品名', '选填,不填则用商品档案名'],
['单位', '选填,不填则用商品档案单位'],
['收藏', '选填,填「是」则该商品排到商城前面'],
],
},
]
);
}
/** 把智能映射后的行转成接口载荷(键为模板表头) */
export function mapMallImportRows(rows?: Record<string, string>[]): MallImportRow[] {
return (rows || [])
.map((row) => ({
sku_code: getCell(row, '商品编码*', '商品编码', '商品代码', '商品编号').trim(),
customer_sku_name: getCell(row, '客户商品名', '商品名称', '品名').trim(),
customer_unit: getCell(row, '单位').trim(),
is_favorite: getCell(row, '收藏', '常用').trim(),
}))
.filter((row) => Boolean(row.sku_code));
}
+86 -2
View File
@@ -6086,6 +6086,90 @@ export async function listCustomerRecipientsApi(customerCode: string) {
}> }>(`/customers/${encodeURIComponent(customerCode)}/recipients`);
}
export type MallLibraryStatus = 'orderable' | 'missing_price' | 'sku_disabled' | 'sku_missing';
export type MallLibraryItem = {
sku_code: string;
display_name: string;
catalog_name: string | null;
spec: string | null;
unit: string;
catalog_unit: string | null;
description: string | null;
sale_price: number | null;
mall_price: number;
price_source: string | null;
on_quote_sheet: boolean;
category_code: string | null;
category_name: string | null;
is_favorite: boolean;
is_listed: boolean;
usage_count: number;
last_order_at: string | null;
sku_status: number | null;
image_url: string | null;
status: MallLibraryStatus;
};
export type MallImportRow = {
sku_code: string;
customer_sku_name: string;
customer_unit: string;
is_favorite: string;
};
export type MallCatalogSku = {
sku_code: string;
sku_name: string;
spec: string | null;
unit: string | null;
category_code: string | null;
category_name: string | null;
image_url: string | null;
};
export async function fetchMallLibraryApi(customerCode: string) {
return workflowFetch<{ data: {
customer: { customer_code: string; company_name: string; branch_code: string | null };
items: MallLibraryItem[];
summary: Record<MallLibraryStatus, number> & { total: number };
} }>(`/customers/${encodeURIComponent(customerCode)}/mall-products`);
}
export async function searchMallCatalogApi(customerCode: string, q = '') {
return workflowFetch<{ data: MallCatalogSku[] }>(
`/customers/${encodeURIComponent(customerCode)}/mall-catalog?q=${encodeURIComponent(q)}`
);
}
export async function addMallLibrarySkusApi(customerCode: string, skuCodes: string[]) {
return workflowFetch<{ data: { added: number; skipped: number; unknown: string[] } }>(
`/customers/${encodeURIComponent(customerCode)}/mall-products`,
{ method: 'POST', body: JSON.stringify({ sku_codes: skuCodes }) }
);
}
export async function updateMallLibraryItemApi(customerCode: string, skuCode: string, body: Record<string, unknown>) {
return workflowFetch<{ data: unknown }>(
`/customers/${encodeURIComponent(customerCode)}/mall-products/${encodeURIComponent(skuCode)}`,
{ method: 'PATCH', body: JSON.stringify(body) }
);
}
export async function removeMallLibrarySkuApi(customerCode: string, skuCode: string) {
return workflowFetch<{ data: { removed: boolean } }>(
`/customers/${encodeURIComponent(customerCode)}/mall-products/${encodeURIComponent(skuCode)}`,
{ method: 'DELETE' }
);
}
export async function previewMallImportApi(customerCode: string, rows: unknown[]) {
return workflowFetch<{ data: {
total: number; will_create: number; will_skip: number; will_fail: number;
duplicates: number; sample_creates: string[]; errors: string[];
} }>(`/customers/${encodeURIComponent(customerCode)}/mall-products/import`, {
method: 'POST', body: JSON.stringify({ dry_run: true, rows }),
});
}
export async function importMallRowsApi(customerCode: string, rows: unknown[]) {
return workflowFetch<{ data: {
created: number; skipped: number; failed: number; duplicates: number; errors: string[];
} }>(`/customers/${encodeURIComponent(customerCode)}/mall-products/import`, {
method: 'POST', body: JSON.stringify({ rows }),
});
}
export async function createCustomerRecipientApi(body: Record<string, unknown>) {
return workflowFetch<{ data: unknown }>('/customers/recipients', { method: 'POST', body: JSON.stringify(body) });
}
@@ -7011,7 +7095,7 @@ export async function setAllocationRulesApi(rules: Partial<AllocationRules>) {
/** 免模板智能导入:读取表头映射记忆 */
export async function getImportMappingMemoryApi(
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier',
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier' | 'mall_product',
signature: string
) {
const query = new URLSearchParams({ signature, _ts: String(Date.now()) });
@@ -7022,7 +7106,7 @@ export async function getImportMappingMemoryApi(
/** 免模板智能导入:保存表头映射记忆 */
export async function saveImportMappingMemoryApi(
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier',
importType: 'sku' | 'category' | 'quote' | 'customer' | 'supplier' | 'mall_product',
body: { signature: string; mapping: Record<string, string>; source_headers: string[] }
) {
return workflowFetch<{ ok: boolean }>(`/import-mappings/${importType}`, {