GoodsManagement.tsx 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. import React, { useState, useCallback, useEffect } from 'react';
  2. import { useQuery, useMutation } from '@tanstack/react-query';
  3. import { format } from 'date-fns';
  4. import { zhCN } from 'date-fns/locale';
  5. import { toast } from 'sonner';
  6. import { zodResolver } from '@hookform/resolvers/zod';
  7. import { useForm } from 'react-hook-form';
  8. import type { InferRequestType, InferResponseType } from 'hono/client';
  9. import { Button } from '@d8d/shared-ui-components/components/ui/button';
  10. import { Input } from '@d8d/shared-ui-components/components/ui/input';
  11. import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
  12. import { RadioGroup, RadioGroupItem } from '@d8d/shared-ui-components/components/ui/radio-group';
  13. import { Label } from '@d8d/shared-ui-components/components/ui/label';
  14. import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
  15. import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
  16. import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
  17. import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
  18. import { Textarea } from '@d8d/shared-ui-components/components/ui/textarea';
  19. import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
  20. import { goodsClient, goodsClientManager } from '../api/goodsClient';
  21. import { AdminCreateGoodsDto, AdminUpdateGoodsDto } from '@d8d/goods-module-mt/schemas';
  22. import { supplierClientManager } from '@d8d/supplier-management-ui-mt/api';
  23. import { merchantClientManager } from '@d8d/merchant-management-ui-mt/api';
  24. import { DataTablePagination } from '@d8d/shared-ui-components/components/admin/DataTablePagination';
  25. import { FileSelector } from '@d8d/file-management-ui-mt';
  26. import { GoodsCategoryCascadeSelector } from '@d8d/goods-category-management-ui-mt/components';
  27. import { SupplierSelector } from '@d8d/supplier-management-ui-mt/components';
  28. import { MerchantSelector } from '@d8d/merchant-management-ui-mt/components';
  29. import { GoodsParentChildPanel, type ParentChildData, type BatchSpecTemplate } from './GoodsParentChildPanel';
  30. import { Search, Plus, Edit, Trash2, Package } from 'lucide-react';
  31. type CreateRequest = InferRequestType<typeof goodsClient.index.$post>['json'];
  32. type UpdateRequest = InferRequestType<typeof goodsClient[':id']['$put']>['json'];
  33. type GoodsResponse = InferResponseType<typeof goodsClient.index.$get, 200>['data'][0];
  34. const createFormSchema = AdminCreateGoodsDto;
  35. const updateFormSchema = AdminUpdateGoodsDto;
  36. export const GoodsManagement: React.FC = () => {
  37. const [searchParams, setSearchParams] = useState({ page: 1, limit: 10, search: '', filter: 'parent' as 'parent' | 'all' });
  38. const [isModalOpen, setIsModalOpen] = useState(false);
  39. const [editingGoods, setEditingGoods] = useState<GoodsResponse | null>(null);
  40. const [isCreateForm, setIsCreateForm] = useState(true);
  41. const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  42. const [goodsToDelete, setGoodsToDelete] = useState<number | null>(null);
  43. const [parentChildData, setParentChildData] = useState({
  44. spuId: 0,
  45. spuName: null as string | null,
  46. childGoodsIds: [] as number[],
  47. batchSpecs: [] as BatchSpecTemplate[]
  48. });
  49. const [isVisible, setIsVisible] = useState(false);
  50. // 创建表单
  51. const createForm = useForm<CreateRequest>({
  52. resolver: zodResolver(createFormSchema),
  53. defaultValues: {
  54. name: '',
  55. price: 0,
  56. costPrice: 0,
  57. categoryId1: 0,
  58. categoryId2: 0,
  59. categoryId3: 0,
  60. goodsType: 1,
  61. supplierId: null,
  62. merchantId: null,
  63. imageFileId: null,
  64. slideImageIds: [],
  65. detail: '',
  66. instructions: '',
  67. sort: 0,
  68. state: 1,
  69. stock: 0,
  70. lowestBuy: 1,
  71. },
  72. });
  73. // 更新表单
  74. const updateForm = useForm<UpdateRequest>({
  75. resolver: zodResolver(updateFormSchema),
  76. });
  77. // 获取商品列表
  78. const { data, isLoading, refetch } = useQuery({
  79. queryKey: ['goods', searchParams],
  80. queryFn: async () => {
  81. const res = await goodsClientManager.get().index.$get({
  82. query: {
  83. page: searchParams.page,
  84. pageSize: searchParams.limit,
  85. keyword: searchParams.search,
  86. ...(searchParams.filter === 'parent' && { filters: '{"spuId": 0}' })
  87. }
  88. });
  89. if (res.status !== 200) throw new Error('获取商品列表失败');
  90. return await res.json();
  91. }
  92. });
  93. // 获取供应商列表(用于默认选择第一个)
  94. const { data: suppliersData, isLoading: isLoadingSuppliers } = useQuery({
  95. queryKey: ['suppliers-for-goods'],
  96. queryFn: async () => {
  97. const res = await supplierClientManager.get().index.$get({
  98. query: {
  99. page: 1,
  100. pageSize: 100
  101. }
  102. });
  103. if (res.status !== 200) throw new Error('获取供应商列表失败');
  104. const result = await res.json();
  105. return result.data || [];
  106. }
  107. });
  108. // 获取商户列表(用于默认选择第一个)
  109. const { data: merchantsData, isLoading: isLoadingMerchants } = useQuery({
  110. queryKey: ['merchants-for-goods'],
  111. queryFn: async () => {
  112. const res = await merchantClientManager.get().index.$get({
  113. query: {
  114. page: 1,
  115. pageSize: 100
  116. }
  117. });
  118. if (res.status !== 200) throw new Error('获取商户列表失败');
  119. const result = await res.json();
  120. return result.data || [];
  121. }
  122. });
  123. // 默认选择第一个供应商和商户(仅创建表单且值为空时)
  124. useEffect(() => {
  125. if (isCreateForm && isModalOpen) {
  126. // 检查是否需要设置默认供应商
  127. const currentSupplierId = createForm.getValues('supplierId');
  128. if (!currentSupplierId && suppliersData && suppliersData.length > 0) {
  129. const firstSupplier = suppliersData[0];
  130. createForm.setValue('supplierId', firstSupplier.id, { shouldValidate: true });
  131. }
  132. // 检查是否需要设置默认商户
  133. const currentMerchantId = createForm.getValues('merchantId');
  134. if (!currentMerchantId && merchantsData && merchantsData.length > 0) {
  135. const firstMerchant = merchantsData[0];
  136. createForm.setValue('merchantId', firstMerchant.id, { shouldValidate: true });
  137. }
  138. }
  139. }, [isCreateForm, isModalOpen, suppliersData, merchantsData, createForm]);
  140. // 创建商品
  141. const createMutation = useMutation({
  142. mutationFn: async (data: CreateRequest) => {
  143. const res = await goodsClientManager.get().index.$post({ json: data });
  144. if (res.status !== 201) throw new Error('创建商品失败');
  145. return await res.json();
  146. },
  147. onSuccess: () => {
  148. toast.success('商品创建成功');
  149. setIsModalOpen(false);
  150. createForm.reset();
  151. refetch();
  152. },
  153. onError: (error) => {
  154. toast.error(error.message || '创建商品失败');
  155. }
  156. });
  157. // 更新商品
  158. const updateMutation = useMutation({
  159. mutationFn: async ({ id, data }: { id: number; data: UpdateRequest }) => {
  160. const res = await goodsClientManager.get()[':id']['$put']({
  161. param: { id: id },
  162. json: data
  163. });
  164. if (res.status !== 200) throw new Error('更新商品失败');
  165. return await res.json();
  166. },
  167. onSuccess: () => {
  168. toast.success('商品更新成功');
  169. setIsModalOpen(false);
  170. setEditingGoods(null);
  171. refetch();
  172. },
  173. onError: (error) => {
  174. toast.error(error.message || '更新商品失败');
  175. }
  176. });
  177. // 删除商品
  178. const deleteMutation = useMutation({
  179. mutationFn: async (id: number) => {
  180. const res = await goodsClientManager.get()[':id']['$delete']({
  181. param: { id: id }
  182. });
  183. if (res.status !== 204) throw new Error('删除商品失败');
  184. return id;
  185. },
  186. onSuccess: () => {
  187. toast.success('商品删除成功');
  188. setDeleteDialogOpen(false);
  189. setGoodsToDelete(null);
  190. refetch();
  191. },
  192. onError: (error) => {
  193. toast.error(error.message || '删除商品失败');
  194. }
  195. });
  196. // 批量创建子商品
  197. const batchCreateChildrenMutation = useMutation({
  198. mutationFn: async ({ parentGoodsId, specs }: { parentGoodsId: number; specs: Array<{ name: string; price: number; costPrice: number; stock: number; sort: number }> }) => {
  199. const res = await goodsClientManager.get().batchCreateChildren.$post({
  200. json: { parentGoodsId, specs }
  201. });
  202. if (res.status !== 200) throw new Error('批量创建子商品失败');
  203. return await res.json();
  204. },
  205. onSuccess: (data) => {
  206. toast.success(`成功创建 ${data.count} 个子商品`);
  207. refetch();
  208. },
  209. onError: (error) => {
  210. toast.error(error.message || '批量创建子商品失败');
  211. }
  212. });
  213. // 处理搜索
  214. const handleSearch = (e: React.FormEvent) => {
  215. e.preventDefault();
  216. setSearchParams(prev => ({ ...prev, page: 1 }));
  217. };
  218. // 处理创建
  219. const handleCreateGoods = () => {
  220. setIsCreateForm(true);
  221. setEditingGoods(null);
  222. createForm.reset();
  223. setIsModalOpen(true);
  224. };
  225. // 处理编辑
  226. const handleEditGoods = (goods: GoodsResponse) => {
  227. setIsCreateForm(false);
  228. setEditingGoods(goods);
  229. updateForm.reset({
  230. name: goods.name,
  231. price: goods.price,
  232. costPrice: goods.costPrice,
  233. categoryId1: goods.categoryId1,
  234. categoryId2: goods.categoryId2,
  235. categoryId3: goods.categoryId3,
  236. goodsType: goods.goodsType,
  237. supplierId: goods.supplierId,
  238. merchantId: goods.merchantId,
  239. imageFileId: goods.imageFileId,
  240. slideImageIds: goods.slideImages?.map(img => img.id) || [],
  241. detail: goods.detail || '',
  242. instructions: goods.instructions || '',
  243. sort: goods.sort,
  244. state: goods.state,
  245. stock: goods.stock,
  246. lowestBuy: goods.lowestBuy,
  247. });
  248. // 更新父子商品数据
  249. setParentChildData({
  250. spuId: goods.spuId,
  251. spuName: goods.parent?.name ?? null,
  252. childGoodsIds: goods.childGoodsIds || [],
  253. batchSpecs: []
  254. });
  255. setIsModalOpen(true);
  256. };
  257. // 处理删除
  258. const handleDeleteGoods = (id: number) => {
  259. setGoodsToDelete(id);
  260. setDeleteDialogOpen(true);
  261. };
  262. // 确认删除
  263. const confirmDelete = () => {
  264. if (goodsToDelete) {
  265. deleteMutation.mutate(goodsToDelete);
  266. }
  267. };
  268. // 提交表单
  269. const handleSubmit = (data: CreateRequest | UpdateRequest) => {
  270. // 合并表单数据和父子商品数据(只合并spuId,childGoodsIds由专门API管理)
  271. const submitData = {
  272. ...data,
  273. spuId: parentChildData.spuId,
  274. // 注意:childGoodsIds不在CreateGoodsDto/UpdateGoodsDto中,由专门API管理
  275. // 不要包含childGoodsIds,否则会导致Zod验证失败
  276. };
  277. if (isCreateForm) {
  278. createMutation.mutate(submitData as CreateRequest, {
  279. onSuccess: (result) => {
  280. // 如果创建成功且有批量创建模板,创建子商品
  281. if (parentChildData.batchSpecs.length > 0 && result.id) {
  282. batchCreateChildrenMutation.mutate({
  283. parentGoodsId: result.id,
  284. specs: parentChildData.batchSpecs
  285. });
  286. }
  287. }
  288. });
  289. } else if (editingGoods) {
  290. updateMutation.mutate({ id: editingGoods.id, data: submitData as UpdateRequest });
  291. }
  292. };
  293. // 处理父子商品数据变化,适配GoodsParentChildPanel的onDataChange类型
  294. const handleParentChildDataChange = useCallback((data: ParentChildData) => {
  295. setParentChildData({
  296. spuId: data.spuId,
  297. spuName: data.spuName ?? null,
  298. childGoodsIds: data.childGoodsIds,
  299. batchSpecs: data.batchSpecs || []
  300. });
  301. }, [setParentChildData]);
  302. return (
  303. <div className="space-y-4">
  304. <div className="flex justify-between items-center">
  305. <h1 className="text-2xl font-bold">商品管理</h1>
  306. <Button onClick={handleCreateGoods} data-testid="create-goods-button">
  307. <Plus className="mr-2 h-4 w-4" />
  308. 创建商品
  309. </Button>
  310. </div>
  311. <Card>
  312. <CardHeader>
  313. <CardTitle>商品列表</CardTitle>
  314. <CardDescription>管理您的商品信息</CardDescription>
  315. </CardHeader>
  316. <CardContent>
  317. <form onSubmit={handleSearch} className="mb-4">
  318. <div className="flex gap-2">
  319. <div className="relative flex-1 max-w-sm">
  320. <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
  321. <Input
  322. placeholder="搜索商品名称..."
  323. value={searchParams.search}
  324. onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
  325. className="pl-8"
  326. />
  327. </div>
  328. <Button type="submit" variant="outline">
  329. 搜索
  330. </Button>
  331. </div>
  332. <div className="mt-4">
  333. <RadioGroup
  334. value={searchParams.filter}
  335. onValueChange={(value) => setSearchParams(prev => ({ ...prev, filter: value as 'parent' | 'all', page: 1 }))}
  336. className="flex gap-4"
  337. >
  338. <div className="flex items-center space-x-2">
  339. <RadioGroupItem value="all" id="filter-all" />
  340. <Label htmlFor="filter-all">显示所有商品</Label>
  341. </div>
  342. <div className="flex items-center space-x-2">
  343. <RadioGroupItem value="parent" id="filter-parent" />
  344. <Label htmlFor="filter-parent">只显示父商品</Label>
  345. </div>
  346. </RadioGroup>
  347. </div>
  348. </form>
  349. <div className="rounded-md border">
  350. <Table>
  351. <TableHeader>
  352. <TableRow>
  353. <TableHead>商品图片</TableHead>
  354. <TableHead>商品名称</TableHead>
  355. <TableHead>价格</TableHead>
  356. <TableHead>库存</TableHead>
  357. <TableHead>销量</TableHead>
  358. <TableHead>供应商</TableHead>
  359. <TableHead>商户</TableHead>
  360. <TableHead>状态</TableHead>
  361. <TableHead>创建时间</TableHead>
  362. <TableHead className="text-right">操作</TableHead>
  363. </TableRow>
  364. </TableHeader>
  365. <TableBody>
  366. {data?.data.map((goods) => (
  367. <TableRow key={goods.id}>
  368. <TableCell>
  369. {goods.imageFile?.fullUrl ? (
  370. <img
  371. src={goods.imageFile.fullUrl}
  372. alt={goods.name}
  373. className="w-12 h-12 object-cover rounded"
  374. />
  375. ) : (
  376. <div className="w-12 h-12 bg-gray-200 rounded flex items-center justify-center">
  377. <Package className="h-6 w-6 text-gray-400" />
  378. </div>
  379. )}
  380. </TableCell>
  381. <TableCell className="font-medium">
  382. <div className="flex flex-col gap-1">
  383. <div>{goods.name}</div>
  384. <div className="flex items-center gap-2">
  385. {goods.spuId === 0 ? (
  386. goods.childGoodsIds?.length > 0 ? (
  387. <>
  388. <Badge variant="outline" className="text-xs">父商品</Badge>
  389. <span className="text-xs text-muted-foreground">
  390. 子商品: {goods.childGoodsIds.length}个
  391. </span>
  392. </>
  393. ) : (
  394. <Badge variant="outline" className="text-xs">单规格</Badge>
  395. )
  396. ) : (
  397. <>
  398. <Badge variant="secondary" className="text-xs">子商品</Badge>
  399. <span className="text-xs text-muted-foreground">
  400. 父商品: {goods.parent?.name || '未知'}
  401. </span>
  402. </>
  403. )}
  404. </div>
  405. </div>
  406. </TableCell>
  407. <TableCell>¥{goods.price.toFixed(2)}</TableCell>
  408. <TableCell>{goods.stock}</TableCell>
  409. <TableCell>{goods.salesNum}</TableCell>
  410. <TableCell>{goods.supplier?.name || '-'}</TableCell>
  411. <TableCell>{goods.merchant?.name || goods.merchant?.username || '-'}</TableCell>
  412. <TableCell>
  413. <Badge variant={goods.state === 1 ? 'default' : 'secondary'}>
  414. {goods.state === 1 ? '可用' : '不可用'}
  415. </Badge>
  416. </TableCell>
  417. <TableCell>
  418. {format(new Date(goods.createdAt), 'yyyy-MM-dd', { locale: zhCN })}
  419. </TableCell>
  420. <TableCell className="text-right">
  421. <div className="flex justify-end gap-2">
  422. <Button
  423. variant="ghost"
  424. size="icon"
  425. onClick={() => handleEditGoods(goods)}
  426. data-testid="edit-goods-button"
  427. >
  428. <Edit className="h-4 w-4" />
  429. </Button>
  430. <Button
  431. variant="ghost"
  432. size="icon"
  433. onClick={() => handleDeleteGoods(goods.id)}
  434. data-testid="delete-goods-button"
  435. >
  436. <Trash2 className="h-4 w-4" />
  437. </Button>
  438. </div>
  439. </TableCell>
  440. </TableRow>
  441. ))}
  442. </TableBody>
  443. </Table>
  444. {data?.data.length === 0 && !isLoading && (
  445. <div className="text-center py-8">
  446. <p className="text-muted-foreground">暂无商品数据</p>
  447. </div>
  448. )}
  449. </div>
  450. <DataTablePagination
  451. currentPage={searchParams.page}
  452. pageSize={searchParams.limit}
  453. totalCount={data?.pagination.total || 0}
  454. onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
  455. />
  456. </CardContent>
  457. </Card>
  458. {/* 创建/编辑对话框 */}
  459. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  460. <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto" data-testid="create-edit-goods-dialog">
  461. <DialogHeader>
  462. <DialogTitle>{isCreateForm ? '创建商品' : '编辑商品'}</DialogTitle>
  463. <DialogDescription>
  464. {isCreateForm ? '创建一个新的商品' : '编辑商品信息'}
  465. </DialogDescription>
  466. </DialogHeader>
  467. {isCreateForm ? (
  468. <Form {...createForm}>
  469. <form id="create-goods-form" onSubmit={createForm.handleSubmit(handleSubmit)} className="space-y-4">
  470. <FormField
  471. control={createForm.control}
  472. name="name"
  473. render={({ field }) => (
  474. <FormItem>
  475. <FormLabel>商品名称 <span className="text-red-500">*</span></FormLabel>
  476. <FormControl>
  477. <Input
  478. placeholder="请输入商品名称"
  479. data-testid="goods-name-input"
  480. {...field}
  481. />
  482. </FormControl>
  483. <FormMessage />
  484. </FormItem>
  485. )}
  486. />
  487. <div className="grid grid-cols-2 gap-4">
  488. <FormField
  489. control={createForm.control}
  490. name="price"
  491. render={({ field }) => (
  492. <FormItem>
  493. <FormLabel>售卖价 <span className="text-red-500">*</span></FormLabel>
  494. <FormControl>
  495. <Input
  496. type="number"
  497. step="0.01"
  498. placeholder="0.00"
  499. data-testid="goods-price-input"
  500. {...field}
  501. />
  502. </FormControl>
  503. <FormMessage />
  504. </FormItem>
  505. )}
  506. />
  507. <FormField
  508. control={createForm.control}
  509. name="costPrice"
  510. render={({ field }) => (
  511. <FormItem>
  512. <FormLabel>成本价 <span className="text-red-500">*</span></FormLabel>
  513. <FormControl>
  514. <Input
  515. type="number"
  516. step="0.01"
  517. placeholder="0.00"
  518. data-testid="goods-cost-price-input"
  519. {...field}
  520. />
  521. </FormControl>
  522. <FormMessage />
  523. </FormItem>
  524. )}
  525. />
  526. </div>
  527. <GoodsCategoryCascadeSelector required={true} />
  528. <div className="grid grid-cols-2 gap-4" style={{ display: 'none' }}>
  529. <FormField
  530. control={createForm.control}
  531. name="supplierId"
  532. render={({ field }) => (
  533. <FormItem>
  534. <FormLabel>供应商</FormLabel>
  535. <FormControl>
  536. <SupplierSelector
  537. value={field.value || undefined}
  538. onChange={field.onChange}
  539. />
  540. </FormControl>
  541. <FormMessage />
  542. </FormItem>
  543. )}
  544. />
  545. <FormField
  546. control={createForm.control}
  547. name="merchantId"
  548. render={({ field }) => (
  549. <FormItem>
  550. <FormLabel>商户</FormLabel>
  551. <FormControl>
  552. <MerchantSelector
  553. value={field.value || undefined}
  554. onChange={field.onChange}
  555. />
  556. </FormControl>
  557. <FormMessage />
  558. </FormItem>
  559. )}
  560. />
  561. </div>
  562. <div className="grid grid-cols-2 gap-4">
  563. <FormField
  564. control={createForm.control}
  565. name="goodsType"
  566. render={({ field }) => (
  567. <FormItem>
  568. <FormLabel>商品类型</FormLabel>
  569. <Select
  570. value={field.value?.toString()}
  571. onValueChange={(value) => field.onChange(parseInt(value))}
  572. >
  573. <FormControl>
  574. <SelectTrigger>
  575. <SelectValue placeholder="选择商品类型" />
  576. </SelectTrigger>
  577. </FormControl>
  578. <SelectContent>
  579. <SelectItem value="1">实物产品</SelectItem>
  580. <SelectItem value="2">虚拟产品</SelectItem>
  581. </SelectContent>
  582. </Select>
  583. <FormMessage />
  584. </FormItem>
  585. )}
  586. />
  587. <FormField
  588. control={createForm.control}
  589. name="stock"
  590. render={({ field }) => (
  591. <FormItem>
  592. <FormLabel>库存 <span className="text-red-500">*</span></FormLabel>
  593. <FormControl>
  594. <Input
  595. type="number"
  596. placeholder="0"
  597. data-testid="goods-stock-input"
  598. {...field}
  599. />
  600. </FormControl>
  601. <FormMessage />
  602. </FormItem>
  603. )}
  604. />
  605. </div>
  606. <FormField
  607. control={createForm.control}
  608. name="sort"
  609. render={({ field }) => (
  610. <FormItem>
  611. <FormLabel>排序</FormLabel>
  612. <FormControl>
  613. <Input type="number" {...field} />
  614. </FormControl>
  615. <FormMessage />
  616. </FormItem>
  617. )}
  618. />
  619. <FormField
  620. control={createForm.control}
  621. name="imageFileId"
  622. render={({ field }) => (
  623. <FormItem>
  624. <FormLabel>商品主图</FormLabel>
  625. <FormControl>
  626. <FileSelector
  627. value={field.value || undefined}
  628. onChange={field.onChange}
  629. maxSize={2}
  630. uploadPath="/goods"
  631. title="上传商品主图"
  632. previewSize="medium"
  633. placeholder="选择商品主图"
  634. filterType="image"
  635. />
  636. </FormControl>
  637. <FormDescription>推荐尺寸:800x800px</FormDescription>
  638. <FormMessage />
  639. </FormItem>
  640. )}
  641. />
  642. <FormField
  643. control={createForm.control}
  644. name="slideImageIds"
  645. render={({ field }) => (
  646. <FormItem>
  647. <FormLabel>商品轮播图</FormLabel>
  648. <FormControl>
  649. <FileSelector
  650. value={field.value || []}
  651. onChange={field.onChange}
  652. allowMultiple={true}
  653. maxSize={5}
  654. uploadPath="/goods/slide"
  655. title="上传轮播图"
  656. previewSize="small"
  657. placeholder="选择商品轮播图"
  658. filterType="image"
  659. />
  660. </FormControl>
  661. <FormDescription>最多上传5张轮播图,推荐尺寸:800x800px</FormDescription>
  662. <FormMessage />
  663. </FormItem>
  664. )}
  665. />
  666. <FormField
  667. control={createForm.control}
  668. name="instructions"
  669. render={({ field }) => (
  670. <FormItem>
  671. <FormLabel>商品简介</FormLabel>
  672. <FormControl>
  673. <Textarea
  674. placeholder="请输入商品简介"
  675. className="resize-none"
  676. {...field}
  677. />
  678. </FormControl>
  679. <FormMessage />
  680. </FormItem>
  681. )}
  682. />
  683. </form>
  684. </Form>
  685. ) : (
  686. <Form {...updateForm}>
  687. <form id="edit-goods-form" onSubmit={updateForm.handleSubmit(handleSubmit)} className="space-y-4">
  688. <FormField
  689. control={updateForm.control}
  690. name="name"
  691. render={({ field }) => (
  692. <FormItem>
  693. <FormLabel>商品名称 <span className="text-red-500">*</span></FormLabel>
  694. <FormControl>
  695. <Input placeholder="请输入商品名称" {...field} />
  696. </FormControl>
  697. <FormMessage />
  698. </FormItem>
  699. )}
  700. />
  701. <div className="grid grid-cols-2 gap-4">
  702. <FormField
  703. control={updateForm.control}
  704. name="price"
  705. render={({ field }) => (
  706. <FormItem>
  707. <FormLabel>售卖价</FormLabel>
  708. <FormControl>
  709. <Input type="number" step="0.01" {...field} />
  710. </FormControl>
  711. <FormMessage />
  712. </FormItem>
  713. )}
  714. />
  715. <FormField
  716. control={updateForm.control}
  717. name="costPrice"
  718. render={({ field }) => (
  719. <FormItem>
  720. <FormLabel>成本价</FormLabel>
  721. <FormControl>
  722. <Input type="number" step="0.01" {...field} />
  723. </FormControl>
  724. <FormMessage />
  725. </FormItem>
  726. )}
  727. />
  728. </div>
  729. <GoodsCategoryCascadeSelector />
  730. <div className="grid grid-cols-2 gap-4">
  731. <FormField
  732. control={updateForm.control}
  733. name="supplierId"
  734. render={({ field }) => (
  735. <FormItem>
  736. <FormLabel>供应商</FormLabel>
  737. <FormControl>
  738. <SupplierSelector
  739. value={field.value || undefined}
  740. onChange={field.onChange}
  741. />
  742. </FormControl>
  743. <FormMessage />
  744. </FormItem>
  745. )}
  746. />
  747. <FormField
  748. control={updateForm.control}
  749. name="merchantId"
  750. render={({ field }) => (
  751. <FormItem>
  752. <FormLabel>商户</FormLabel>
  753. <FormControl>
  754. <MerchantSelector
  755. value={field.value || undefined}
  756. onChange={field.onChange}
  757. />
  758. </FormControl>
  759. <FormMessage />
  760. </FormItem>
  761. )}
  762. />
  763. </div>
  764. <div className="grid grid-cols-2 gap-4">
  765. <FormField
  766. control={updateForm.control}
  767. name="stock"
  768. render={({ field }) => (
  769. <FormItem>
  770. <FormLabel>库存</FormLabel>
  771. <FormControl>
  772. <Input type="number" {...field} />
  773. </FormControl>
  774. <FormMessage />
  775. </FormItem>
  776. )}
  777. />
  778. <FormField
  779. control={updateForm.control}
  780. name="state"
  781. render={({ field }) => (
  782. <FormItem>
  783. <FormLabel>状态</FormLabel>
  784. <Select
  785. value={field.value?.toString()}
  786. onValueChange={(value) => field.onChange(parseInt(value))}
  787. >
  788. <FormControl>
  789. <SelectTrigger>
  790. <SelectValue />
  791. </SelectTrigger>
  792. </FormControl>
  793. <SelectContent>
  794. <SelectItem value="1">可用</SelectItem>
  795. <SelectItem value="2">不可用</SelectItem>
  796. </SelectContent>
  797. </Select>
  798. <FormMessage />
  799. </FormItem>
  800. )}
  801. />
  802. </div>
  803. <FormField
  804. control={updateForm.control}
  805. name="sort"
  806. render={({ field }) => (
  807. <FormItem>
  808. <FormLabel>排序</FormLabel>
  809. <FormControl>
  810. <Input type="number" {...field} />
  811. </FormControl>
  812. <FormMessage />
  813. </FormItem>
  814. )}
  815. />
  816. <FormField
  817. control={updateForm.control}
  818. name="imageFileId"
  819. render={({ field }) => (
  820. <FormItem>
  821. <FormLabel>商品主图</FormLabel>
  822. <FormControl>
  823. <FileSelector
  824. value={field.value || undefined}
  825. onChange={field.onChange}
  826. maxSize={2}
  827. uploadPath="/goods"
  828. title="上传商品主图"
  829. previewSize="medium"
  830. placeholder="选择商品主图"
  831. filterType="image"
  832. />
  833. </FormControl>
  834. <FormDescription>推荐尺寸:800x800px</FormDescription>
  835. <FormMessage />
  836. </FormItem>
  837. )}
  838. />
  839. <FormField
  840. control={updateForm.control}
  841. name="slideImageIds"
  842. render={({ field }) => (
  843. <FormItem>
  844. <FormLabel>商品轮播图</FormLabel>
  845. <FormControl>
  846. <FileSelector
  847. value={field.value || []}
  848. onChange={field.onChange}
  849. allowMultiple={true}
  850. maxSize={5}
  851. uploadPath="/goods/slide"
  852. title="上传轮播图"
  853. previewSize="small"
  854. placeholder="选择商品轮播图"
  855. filterType="image"
  856. />
  857. </FormControl>
  858. <FormDescription>最多上传5张轮播图,推荐尺寸:800x800px</FormDescription>
  859. <FormMessage />
  860. </FormItem>
  861. )}
  862. />
  863. <FormField
  864. control={updateForm.control}
  865. name="instructions"
  866. render={({ field }) => (
  867. <FormItem>
  868. <FormLabel>商品简介</FormLabel>
  869. <FormControl>
  870. <Textarea
  871. placeholder="请输入商品简介"
  872. className="resize-none"
  873. {...field}
  874. />
  875. </FormControl>
  876. <FormMessage />
  877. </FormItem>
  878. )}
  879. />
  880. </form>
  881. </Form>
  882. )}
  883. {/* 父子商品管理面板 - 移到表单下方 */}
  884. <div className="mt-6 pt-6 border-t">
  885. <GoodsParentChildPanel
  886. mode={isCreateForm ? 'create' : 'edit'}
  887. goodsId={isCreateForm ? undefined : editingGoods?.id}
  888. goodsName={isCreateForm ? createForm.watch('name') : editingGoods?.name}
  889. spuId={parentChildData.spuId}
  890. spuName={parentChildData.spuName ?? undefined}
  891. childGoodsIds={parentChildData.childGoodsIds}
  892. batchSpecs={isCreateForm ? parentChildData.batchSpecs : undefined}
  893. onDataChange={handleParentChildDataChange}
  894. onUpdate={refetch}
  895. disabled={isCreateForm ? createMutation.isPending : updateMutation.isPending}
  896. />
  897. </div>
  898. {/* 对话框底部按钮 */}
  899. <DialogFooter>
  900. <Button
  901. type="button"
  902. variant="outline"
  903. onClick={() => setIsModalOpen(false)}
  904. >
  905. 取消
  906. </Button>
  907. <Button
  908. type="submit"
  909. form={isCreateForm ? "create-goods-form" : "edit-goods-form"}
  910. disabled={isCreateForm ? createMutation.isPending : updateMutation.isPending}
  911. >
  912. {isCreateForm
  913. ? (createMutation.isPending ? '创建中...' : '创建')
  914. : (updateMutation.isPending ? '更新中...' : '更新')
  915. }
  916. </Button>
  917. </DialogFooter>
  918. </DialogContent>
  919. </Dialog>
  920. {/* 删除确认对话框 */}
  921. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  922. <DialogContent>
  923. <DialogHeader>
  924. <DialogTitle>确认删除</DialogTitle>
  925. <DialogDescription>
  926. 确定要删除这个商品吗?此操作无法撤销。
  927. </DialogDescription>
  928. </DialogHeader>
  929. <DialogFooter>
  930. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  931. 取消
  932. </Button>
  933. <Button
  934. variant="destructive"
  935. onClick={confirmDelete}
  936. disabled={deleteMutation.isPending}
  937. >
  938. {deleteMutation.isPending ? '删除中...' : '删除'}
  939. </Button>
  940. </DialogFooter>
  941. </DialogContent>
  942. </Dialog>
  943. </div>
  944. );
  945. };